C # Generic Dictionary

Source: Internet
Author: User

1. namespace:
   System. Collections. Generic (Assembly: mscorlib)
2. Description:
1) ing from a group of keys to a group of values. Each add item is composed of a Value and its associated keys.
2) any key must be unique.
3) The key cannot be null reference null (in VBNothing). If the value is of the reference type, it can be null.
4), the Key and Value can be of any type (string, int, custom class, etc)
3. Creation and initialization:
   Dictionary <int, string> myDictionary = new Dictionary <int, string> ();
4. Add elements:
MyDictionary. Add ("C #", 0 );
MyDictionary. Add ("C ++", 1 );
MyDictionary. Add ("C", 2 );
MyDictionary. Add ("VB", 2 );
5. Search for the element By Key:
If (myDictionary. ContainsKey ("C #"))
{
Console. WriteLine ("Key: {0}, Value: {1}", "C #", myDictionary ["C #"]);
}
6. traverse the element By KeyValuePair
Foreach (KeyValuePair <string, int> kvp in myDictionary)
{
Console. WriteLine ("Key = {0}, Value = {1}", kvp. Key, kvp. Value );
}
7. Only traverse the key By Keys attribute:
Dictionary <string, int>. KeyCollection keyCol = myDictionary. Keys;
Foreach (string key in keyCol/* string key in myDictionary. Keys */)
{
Console. WriteLine ("Key = {0}", key );
}
8. Only traverse the value By Valus attribute:
Dictionary <string, int>. ValueCollection valueCol = myDictionary. Values;
Foreach (int value in valueCol)
{
Console. WriteLine ("Value = {0}", value );
}
9. Remove the specified key value By Remove method:
MyDictionary. Remove ("C #");
If (myDictionary. ContainsKey ("C #"))
{
Console. WriteLine ("Key: {0}, Value: {1}", "C #", myDictionary ["C #"]);
}
Else
{
Console. WriteLine ("Key: C #" does not exist #");
 

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.