Two ways to traverse a dictionary

Source: Internet
Author: User

Dictionary <string, int> things = new dictionary <string, int> ();

Things. Add (........);

Things. Add (........);

 

 

Method 1: You can use the keys and values attributes to iterate the keys and values in the Set:

Foreach (string key in things. Keys)

{

//......

}

Or

Foreach (INT value in things. values)

{

//....

}

Method 2: You can also iterate each item in the set and use each item as a keyvaluepair <K, V> instance.

Foreach (keyvaluepair <string, int> thing in things)

{

Console. writeline ("{0 }={ 1}", thing. Key, thing. value );

}

 

In addition, the keys of dictionary <K, V> cannot be repeated. If the same key is added, an argumentexception exception is thrown.

However, there may be an application where the key acts as a commodity name or name, which is case-insensitive (should be treated as the same commodity or character), but we use it as the key

If an exception is thrown during addition, it violates our business logic concept (our names or product names are case-insensitive, that is, names with different cases should be treated as the same key)

Solution: when new dictionary is used, the icomparer <k> interface can be passed to the constructor. In the icomparer <k> interface, we can compare each name (for example, convert to lowercase and then compare ).

In this way, you can.

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.