In C #, Dictionary provides quick, part-based element lookups. You can use it when you have a lot of elements. It is contained in the System.Collections.Generic name space.
Before you use it, you must declare its key type and value type.
Detailed description
Must contain a name space System.Collection.Generic
Each element in the dictionary is a key-value pair (consisting of two elements: a key and a value)
The key must be unique, and the value does not require a unique
Both the key and the value can be of any type (e.g. string, int, custom type, etc.)
The time to read a value through a key is close to O (1)
The partial order between key-value pairs can be undefined.
Create and initialize a Dictionary object
dictionary<int,string> mydictionary = new Dictionary<int, string= "" > ();
Add key
static void Main (string[] args)
{
Dictionary<string, int= "" > D = new dictionary<string, int= "" > ();
D.add ("C #", 2);
D.add ("C", 0);
D.add ("C + +",-1);
}
Find key
static void Main (string[] args)
{
dictionary<string, int= "" > d = New dictionary<string, int= "" > ();
D.add ("C #", 2);
d.add ("VB", 1);
d.add ("C", 0),
D.add ("C + +",-1);
if (d. ContainsKey ("VB"))//true
{
int p = d["vb"];&NBSP;
Console.WriteLine (P);
}
&NBSP
if (D.containskey ("C"))
{
int p1 = d["C"];&NBSP;
Console.WriteLine (p1) ;
}
}
Delete Element
static void Main (string[] args)
{
Dictionary<string, int= "" > D = new dictionary<string, int= "" > ();
D.add ("C #", 2);
D.add ("VB", 1);
D.add ("C", 0);
D.add ("C + +",-1);
D.remove ("C");
D.remove ("VB");
}
Use Containsvalue to find the existence of a value
static void Main (string[] args)
{
Dictionary<string, int= "" > D = new dictionary<string, int= "" > ();
D.add ("C #", 2);
D.add ("VB", 1);
D.add ("C", 0);
D.add ("C + +",-1);
if (D.containsvalue (1))
{
Console.WriteLine ("VB");
}
if (D.containsvalue (2))
{
Console.WriteLine ("C #");
}
if (d.containsvalue (0))
{
Console.WriteLine ("C");
}
if (D.containsvalue (-1))
{
Console.WriteLine ("C + +");
}
}
KeyNotFoundException
If you try to read a non-existent key in the dictionary, you will get a keynotfoundexception. All before reading a key, you must first use Containkey to check if the key exists in the dictionary.
Dictionary based on the INT key
static void Main (string[] args)
{
Dictionary<int, string= "" > D = new dictionary<int, string= "" > ();
D.add ("Planet");
D.add ("Stars");
Lookup the int in the dictionary.
if (D.containskey (1000))
{
Console.WriteLine (True);
}
Console.ReadLine ();
}
Sort dictionary SortedDictionary
In the sort dictionary, the dictionary must be sorted when the element is added, so the insertion speed is slower. But because elements are stored in an orderly fashion, searching for elements can use some more efficient searches such as binary search.
Http://www.cnblogs.com/ccczqh/archive/2011/01/04/1925852.html
Introduction to C # Dictionary