Collections C# Book

IDictionary defines the standard protocol for all key/value-based col- lections.

public interface IDictionary :
ICollection >, IEnumerable
{
bool ContainsKey (TKey key);
bool TryGetValue (TKey key, out TValue value);
void Add (TKey key, TValue value);
bool Remove (TKey key);

TValue this [TKey key] { get; set; } // Main indexer - by key ICollection
Keys { get; } // Returns just keys
ICollection Values { get; } // Returns just values
}
Enumerating directly over an IDictionary returns a sequence of KeyValuePair structs:

public struct KeyValuePair
{
public TKey Key { get; }
public TValue Value { get; }
}
Here's how to use it:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Sample
{
public static void Main()
{
var d = new Dictionary();
d.Add("One", 1);
d["Two"] = 2; // adds to dictionary
d["Two"] = 4; // updates dictionary
d["Three"] = 3;
Console.WriteLine(d["Two"]);
Console.WriteLine(d.ContainsKey("One")); // true (fast operation)
Console.WriteLine(d.ContainsValue(3)); // true (slow operation)
int val = 0;
if (!d.TryGetValue("onE", out val)){
Console.WriteLine("No value"); // "No val" (case sensitive)
}
}
}
The output:
4
True
True
No value