Using System;
Using System. Collections. Generic;
Class DictionaryDemo
{
Static void Main (string [] args)
{
DictionaryDemo001 ();
Console. ReadLine ();
DictionaryDemo002 ();
Console. ReadLine ();
DictionaryDemo003 ();
Console. ReadLine ();
}
/// <Summary>
/// General Usage
/// </Summary>
Static void DictionaryDemo001 ()
{
Dictionary <int, string> dict = new Dictionary <int, string> ();
Dict. Add (1, "111 ");
Dict. Add (2, "222 ");
// Determine whether the corresponding key exists and display it
If (dict. ContainsKey (2 ))
{
Console. WriteLine (dict [2]);
}
// Traverse Keys
Foreach (var item in dict. Keys)
{
Console. WriteLine ("Key: {0}", item );
}
// Traverse Values
Foreach (var item in dict. Values)
{
Console. WriteLine ("value: {0}", item );
}
// Traverse the entire dictionary
Foreach (var item in dict)
{
Console. WriteLine ("key: {0} value: {1}", item. Key, item. Value );
}
}
/// <Summary>
/// The parameter is of another type
/// </Summary>
Static void DictionaryDemo002 ()
{
Dictionary <string, string []> dict = new Dictionary <string, string []> ();
Dict. Add ("1", "1, 11, 111". Split (','));
Dict. Add ("2", "2,22, 222". Split (','));
Console. WriteLine (dict ["2"] [2]);
}
/// <Summary>
/// Call a custom class
/// </Summary>
Static void DictionaryDemo003 ()
{
Dictionary <int, yongfa365> dict = new Dictionary <int, yongfa365> ();
For (int I = 0; I <10; I ++)
{
Yongfa365 y = new yongfa365 ();
Y. UserCode = I;
Y. UserName = "www.yongfa365.com" + I. ToString ();
Dict. Add (I, y );
}
Foreach (var item in dict)
{
Console. WriteLine ("{0} One: {1} UserName: {2}", item. Key, item. Value. UserCode, item. Value. UserName );
}
}
}
Class yongfa365
{
Public int UserCode {get; set ;}
Public string UserName {get; set ;}
}
From Mr. Shaw