C # Dictionary usage

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.