IDictionary<TKey,TValue> インターフェイス
定義
重要
一部の情報は、リリース前に大きく変更される可能性があるプレリリースされた製品に関するものです。 Microsoft は、ここに記載されている情報について、明示または黙示を問わず、一切保証しません。
キーと値のペアのジェネリック コレクションを表します。
generic <typename TKey, typename TValue>
public interface class IDictionary : System::Collections::Generic::ICollection<System::Collections::Generic::KeyValuePair<TKey, TValue>>, System::Collections::Generic::IEnumerable<System::Collections::Generic::KeyValuePair<TKey, TValue>>
public interface IDictionary<TKey,TValue> : System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey,TValue>>
type IDictionary<'Key, 'Value> = interface
interface ICollection<KeyValuePair<'Key, 'Value>>
interface seq<KeyValuePair<'Key, 'Value>>
interface IEnumerable
Public Interface IDictionary(Of TKey, TValue)
Implements ICollection(Of KeyValuePair(Of TKey, TValue)), IEnumerable(Of KeyValuePair(Of TKey, TValue))
型パラメーター
- TKey
ディクショナリ内のキーの種類。
- TValue
ディクショナリ内の値の型。
- 派生
- 実装
-
ICollection<KeyValuePair<TKey,TValue>> IEnumerable<KeyValuePair<TKey,TValue>> IEnumerable<T> IEnumerable
例
次のコード例では、文字列キーを使用して文字列の空の Dictionary<TKey,TValue> を作成し、IDictionary<TKey,TValue> インターフェイスを介してアクセスします。
このコード例では、Add メソッドを使用していくつかの要素を追加します。 この例では、重複するキーを追加しようとしたときに、Add メソッドが ArgumentException をスローすることを示します。
この例では、Item[] プロパティ (C# のインデクサー) を使用して値を取得し、要求されたキーが存在しない場合に KeyNotFoundException がスローされることを示し、キーに関連付けられている値を置き換えることができることを示しています。
この例では、TryGetValue メソッドを使用して、プログラムがディクショナリにないキー値を頻繁に試す必要がある場合に値を取得するより効率的な方法を示し、ContainsKey メソッドを使用して、Add メソッドを呼び出す前にキーが存在するかどうかをテストする方法を示します。
最後に、ディクショナリ内のキーと値を列挙する方法と、Values プロパティを使用して値を列挙する方法を示します。
using namespace System;
using namespace System::Collections::Generic;
public ref class Example
{
public:
static void Main()
{
// Create a new dictionary of strings, with string keys,
// and access it through the IDictionary generic interface.
IDictionary<String^, String^>^ openWith =
gcnew Dictionary<String^, String^>();
// Add some elements to the dictionary. There are no
// duplicate keys, but some of the values are duplicates.
openWith->Add("txt", "notepad.exe");
openWith->Add("bmp", "paint.exe");
openWith->Add("dib", "paint.exe");
openWith->Add("rtf", "wordpad.exe");
// The Add method throws an exception if the new key is
// already in the dictionary.
try
{
openWith->Add("txt", "winword.exe");
}
catch (ArgumentException^)
{
Console::WriteLine("An element with Key = \"txt\" already exists.");
}
// The Item property is another name for the indexer, so you
// can omit its name when accessing elements.
Console::WriteLine("For key = \"rtf\", value = {0}.",
openWith["rtf"]);
// The indexer can be used to change the value associated
// with a key.
openWith["rtf"] = "winword.exe";
Console::WriteLine("For key = \"rtf\", value = {0}.",
openWith["rtf"]);
// If a key does not exist, setting the indexer for that key
// adds a new key/value pair.
openWith["doc"] = "winword.exe";
// The indexer throws an exception if the requested key is
// not in the dictionary.
try
{
Console::WriteLine("For key = \"tif\", value = {0}.",
openWith["tif"]);
}
catch (KeyNotFoundException^)
{
Console::WriteLine("Key = \"tif\" is not found.");
}
// When a program often has to try keys that turn out not to
// be in the dictionary, TryGetValue can be a more efficient
// way to retrieve values.
String^ value = "";
if (openWith->TryGetValue("tif", value))
{
Console::WriteLine("For key = \"tif\", value = {0}.", value);
}
else
{
Console::WriteLine("Key = \"tif\" is not found.");
}
// ContainsKey can be used to test keys before inserting
// them.
if (!openWith->ContainsKey("ht"))
{
openWith->Add("ht", "hypertrm.exe");
Console::WriteLine("Value added for key = \"ht\": {0}",
openWith["ht"]);
}
// When you use foreach to enumerate dictionary elements,
// the elements are retrieved as KeyValuePair objects.
Console::WriteLine();
for each( KeyValuePair<String^, String^> kvp in openWith )
{
Console::WriteLine("Key = {0}, Value = {1}",
kvp.Key, kvp.Value);
}
// To get the values alone, use the Values property.
ICollection<String^>^ icoll = openWith->Values;
// The elements of the ValueCollection are strongly typed
// with the type that was specified for dictionary values.
Console::WriteLine();
for each( String^ s in icoll )
{
Console::WriteLine("Value = {0}", s);
}
// To get the keys alone, use the Keys property.
icoll = openWith->Keys;
// The elements of the ValueCollection are strongly typed
// with the type that was specified for dictionary values.
Console::WriteLine();
for each( String^ s in icoll )
{
Console::WriteLine("Key = {0}", s);
}
// Use the Remove method to remove a key/value pair.
Console::WriteLine("\nRemove(\"doc\")");
openWith->Remove("doc");
if (!openWith->ContainsKey("doc"))
{
Console::WriteLine("Key \"doc\" is not found.");
}
}
};
int main()
{
Example::Main();
}
/* This code example produces the following output:
An element with Key = "txt" already exists.
For key = "rtf", value = wordpad.exe.
For key = "rtf", value = winword.exe.
Key = "tif" is not found.
Key = "tif" is not found.
Value added for key = "ht": hypertrm.exe
Key = txt, Value = notepad.exe
Key = bmp, Value = paint.exe
Key = dib, Value = paint.exe
Key = rtf, Value = winword.exe
Key = doc, Value = winword.exe
Key = ht, Value = hypertrm.exe
Value = notepad.exe
Value = paint.exe
Value = paint.exe
Value = winword.exe
Value = winword.exe
Value = hypertrm.exe
Key = txt
Key = bmp
Key = dib
Key = rtf
Key = doc
Key = ht
Remove("doc")
Key "doc" is not found.
*/
using System;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
// Create a new dictionary of strings, with string keys,
// and access it through the IDictionary generic interface.
IDictionary<string, string> openWith =
new Dictionary<string, string>();
// Add some elements to the dictionary. There are no
// duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");
// The Add method throws an exception if the new key is
// already in the dictionary.
try
{
openWith.Add("txt", "winword.exe");
}
catch (ArgumentException)
{
Console.WriteLine("An element with Key = \"txt\" already exists.");
}
// The Item property is another name for the indexer, so you
// can omit its name when accessing elements.
Console.WriteLine("For key = \"rtf\", value = {0}.",
openWith["rtf"]);
// The indexer can be used to change the value associated
// with a key.
openWith["rtf"] = "winword.exe";
Console.WriteLine("For key = \"rtf\", value = {0}.",
openWith["rtf"]);
// If a key does not exist, setting the indexer for that key
// adds a new key/value pair.
openWith["doc"] = "winword.exe";
// The indexer throws an exception if the requested key is
// not in the dictionary.
try
{
Console.WriteLine("For key = \"tif\", value = {0}.",
openWith["tif"]);
}
catch (KeyNotFoundException)
{
Console.WriteLine("Key = \"tif\" is not found.");
}
// When a program often has to try keys that turn out not to
// be in the dictionary, TryGetValue can be a more efficient
// way to retrieve values.
string value = "";
if (openWith.TryGetValue("tif", out value))
{
Console.WriteLine("For key = \"tif\", value = {0}.", value);
}
else
{
Console.WriteLine("Key = \"tif\" is not found.");
}
// ContainsKey can be used to test keys before inserting
// them.
if (!openWith.ContainsKey("ht"))
{
openWith.Add("ht", "hypertrm.exe");
Console.WriteLine("Value added for key = \"ht\": {0}",
openWith["ht"]);
}
// When you use foreach to enumerate dictionary elements,
// the elements are retrieved as KeyValuePair objects.
Console.WriteLine();
foreach( KeyValuePair<string, string> kvp in openWith )
{
Console.WriteLine("Key = {0}, Value = {1}",
kvp.Key, kvp.Value);
}
// To get the values alone, use the Values property.
ICollection<string> icoll = openWith.Values;
// The elements of the ValueCollection are strongly typed
// with the type that was specified for dictionary values.
Console.WriteLine();
foreach( string s in icoll )
{
Console.WriteLine("Value = {0}", s);
}
// To get the keys alone, use the Keys property.
icoll = openWith.Keys;
// The elements of the ValueCollection are strongly typed
// with the type that was specified for dictionary values.
Console.WriteLine();
foreach( string s in icoll )
{
Console.WriteLine("Key = {0}", s);
}
// Use the Remove method to remove a key/value pair.
Console.WriteLine("\nRemove(\"doc\")");
openWith.Remove("doc");
if (!openWith.ContainsKey("doc"))
{
Console.WriteLine("Key \"doc\" is not found.");
}
}
}
/* This code example produces the following output:
An element with Key = "txt" already exists.
For key = "rtf", value = wordpad.exe.
For key = "rtf", value = winword.exe.
Key = "tif" is not found.
Key = "tif" is not found.
Value added for key = "ht": hypertrm.exe
Key = txt, Value = notepad.exe
Key = bmp, Value = paint.exe
Key = dib, Value = paint.exe
Key = rtf, Value = winword.exe
Key = doc, Value = winword.exe
Key = ht, Value = hypertrm.exe
Value = notepad.exe
Value = paint.exe
Value = paint.exe
Value = winword.exe
Value = winword.exe
Value = hypertrm.exe
Key = txt
Key = bmp
Key = dib
Key = rtf
Key = doc
Key = ht
Remove("doc")
Key "doc" is not found.
*/
Imports System.Collections.Generic
Public Class Example
Public Shared Sub Main()
' Create a new dictionary of strings, with string keys,
' and access it through the IDictionary generic interface.
Dim openWith As IDictionary(Of String, String) = _
New Dictionary(Of String, String)
' Add some elements to the dictionary. There are no
' duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe")
openWith.Add("bmp", "paint.exe")
openWith.Add("dib", "paint.exe")
openWith.Add("rtf", "wordpad.exe")
' The Add method throws an exception if the new key is
' already in the dictionary.
Try
openWith.Add("txt", "winword.exe")
Catch
Console.WriteLine("An element with Key = ""txt"" already exists.")
End Try
' The Item property is the default property, so you
' can omit its name when accessing elements.
Console.WriteLine("For key = ""rtf"", value = {0}.", _
openWith("rtf"))
' The default Item property can be used to change the value
' associated with a key.
openWith("rtf") = "winword.exe"
Console.WriteLine("For key = ""rtf"", value = {0}.", _
openWith("rtf"))
' If a key does not exist, setting the default item property
' for that key adds a new key/value pair.
openWith("doc") = "winword.exe"
' The default Item property throws an exception if the requested
' key is not in the dictionary.
Try
Console.WriteLine("For key = ""tif"", value = {0}.", _
openWith("tif"))
Catch
Console.WriteLine("Key = ""tif"" is not found.")
End Try
' When a program often has to try keys that turn out not to
' be in the dictionary, TryGetValue can be a more efficient
' way to retrieve values.
Dim value As String = ""
If openWith.TryGetValue("tif", value) Then
Console.WriteLine("For key = ""tif"", value = {0}.", value)
Else
Console.WriteLine("Key = ""tif"" is not found.")
End If
' ContainsKey can be used to test keys before inserting
' them.
If Not openWith.ContainsKey("ht") Then
openWith.Add("ht", "hypertrm.exe")
Console.WriteLine("Value added for key = ""ht"": {0}", _
openWith("ht"))
End If
' When you use foreach to enumerate dictionary elements,
' the elements are retrieved as KeyValuePair objects.
Console.WriteLine()
For Each kvp As KeyValuePair(Of String, String) In openWith
Console.WriteLine("Key = {0}, Value = {1}", _
kvp.Key, kvp.Value)
Next kvp
' To get the values alone, use the Values property.
Dim icoll As ICollection(Of String) = openWith.Values
' The elements of the ValueCollection are strongly typed
' with the type that was specified for dictionary values.
Console.WriteLine()
For Each s As String In icoll
Console.WriteLine("Value = {0}", s)
Next s
' To get the keys alone, use the Keys property.
icoll = openWith.Keys
' The elements of the ValueCollection are strongly typed
' with the type that was specified for dictionary values.
Console.WriteLine()
For Each s As String In icoll
Console.WriteLine("Key = {0}", s)
Next s
' Use the Remove method to remove a key/value pair.
Console.WriteLine(vbLf + "Remove(""doc"")")
openWith.Remove("doc")
If Not openWith.ContainsKey("doc") Then
Console.WriteLine("Key ""doc"" is not found.")
End If
End Sub
End Class
' This code example produces the following output:
'
'An element with Key = "txt" already exists.
'For key = "rtf", value = wordpad.exe.
'For key = "rtf", value = winword.exe.
'Key = "tif" is not found.
'Key = "tif" is not found.
'Value added for key = "ht": hypertrm.exe
'
'Key = txt, Value = notepad.exe
'Key = bmp, Value = paint.exe
'Key = dib, Value = paint.exe
'Key = rtf, Value = winword.exe
'Key = doc, Value = winword.exe
'Key = ht, Value = hypertrm.exe
'
'Value = notepad.exe
'Value = paint.exe
'Value = paint.exe
'Value = winword.exe
'Value = winword.exe
'Value = hypertrm.exe
'
'Key = txt
'Key = bmp
'Key = dib
'Key = rtf
'Key = doc
'Key = ht
'
'Remove("doc")
'Key "doc" is not found.
'
注釈
IDictionary<TKey,TValue> インターフェイスは、キーと値のペアのジェネリック コレクションの基本インターフェイスです。
各要素は、KeyValuePair<TKey,TValue> オブジェクトに格納されているキーと値のペアです。
各ペアには一意のキーが必要です。 実装は、key
を null
できるかどうかによって異なる場合があります。 値は null
することができ、一意である必要はありません。
IDictionary<TKey,TValue> インターフェイスでは、含まれているキーと値を列挙できますが、特定の並べ替え順序を意味するものではありません。
C# 言語の foreach
ステートメント (Visual Basic ではFor Each
、C++ では for each
) は、コレクション内の要素の型のオブジェクトを返します。
IDictionary<TKey,TValue> の各要素はキーと値のペアであるため、要素の型はキーの型または値の型ではありません。 代わりに、要素型は KeyValuePair<TKey,TValue>です。 例えば:
for each(KeyValuePair<int, String^> kvp in myDictionary)
{
Console::WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
foreach (KeyValuePair<int, string> kvp in myDictionary)
{
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
For Each kvp As KeyValuePair(Of Integer, String) In myDictionary
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value)
Next kvp
foreach
ステートメントは列挙子のラッパーであり、コレクションへの書き込みではなく、コレクションからの読み取りのみが許可されます。
手記
キーを継承して動作を変更できるため、Equals メソッドを使用した比較では、その絶対一意性を保証できません。
注意 (実装者)
実装クラスには、キーを比較する手段が必要です。
プロパティ
Count |
ICollection<T>に含まれる要素の数を取得します。 (継承元 ICollection<T>) |
IsReadOnly |
ICollection<T> が読み取り専用かどうかを示す値を取得します。 (継承元 ICollection<T>) |
Item[TKey] |
指定したキーを持つ要素を取得または設定します。 |
Keys |
IDictionary<TKey,TValue>のキーを含む ICollection<T> を取得します。 |
Values |
IDictionary<TKey,TValue>内の値を含む ICollection<T> を取得します。 |
メソッド
Add(T) |
ICollection<T>に項目を追加します。 (継承元 ICollection<T>) |
Add(TKey, TValue) |
指定されたキーと値を持つ要素を IDictionary<TKey,TValue>に追加します。 |
Clear() |
ICollection<T>からすべての項目を削除します。 (継承元 ICollection<T>) |
Contains(T) |
ICollection<T> に特定の値が含まれているかどうかを判断します。 (継承元 ICollection<T>) |
ContainsKey(TKey) |
指定したキーを持つ要素が IDictionary<TKey,TValue> に含まれているかどうかを判断します。 |
CopyTo(T[], Int32) |
特定の Array インデックスから始まる ICollection<T> の要素を Arrayにコピーします。 (継承元 ICollection<T>) |
GetEnumerator() |
コレクションを反復処理する列挙子を返します。 (継承元 IEnumerable) |
Remove(TKey) |
指定したキーを持つ要素を IDictionary<TKey,TValue>から削除します。 |
TryGetValue(TKey, TValue) |
指定したキーに関連付けられている値を取得します。 |
拡張メソッド
適用対象
こちらもご覧ください
.NET