Mega Code Archive

 
Categories / C# Book / 03 Collections
 

0366 Generic IDictionary

IDictionary<TKey,TValue> defines the standard protocol for all key/value-based col- lections. public interface IDictionary <TKey, TValue> : ICollection <KeyValuePair <TKey, TValue>>, 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 <TKey> Keys { get; } // Returns just keys ICollection <TValue> Values { get; } // Returns just values } Enumerating directly over an IDictionary<TKey,TValue> returns a sequence of KeyValuePair structs: public struct KeyValuePair <TKey, TValue> { 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<string, int>(); 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