C # ordered list of sets,

Source: Internet
Author: User

C # ordered list of sets,

If you need to sort the required set based on the key pair, you can use the SortedList <TKey, TValue> class. This class sorts the elements by key. The values and keys in this set can all be of any type. The IComparer <T> interface must be implemented for the custom type defined as a key to sort the elements in the list.
Create an ordered list using the constructor and Add it using the Add method:
Var books = new SortedList <string, string> ();
Books. Add ("Professional WPF Programming", "978-0-470-04180-2 ");
Books. Add ("Professional ASP. net mvc 3", "978-1-1180-7658-3 ");
You can also use the indexer to add elements to the list.
Books ["Beginning Visual C #2010"] = "978-0-470-50226-6 ";
Books ["Professional C #4 and. NET 4"] = "978-0-470-50225-9 ";
SortedList <TKey, TValue> has multiple overloaded constructors.

You can use the foreach statement to traverse the list. The element returned by the enumerator is of the KeyValuePair <TKey, TValue> type, which includes the key and value:
Foreach (KeyValuePair <string, string> book in books)
{
Console. WriteLine ("{0}, {1}", book. Key, book. Value );
}
The iteration statement is displayed in the order of keys:
Beginning Visual C #2010,978-0-470-50226-6
Professional ASP. net mvc 3,978-1-1180-7658-3
Professional C #4 and. NET 4,978-0-470-50225-9
Professional WPF Programming, 978-0-470-04180-2

You can also use the Values and Keys attributes to access Values and Keys:
Foreach (string isbn in books. Values)
{
Console. WriteLine (isbn );
}

Foreach (string title in books. Keys)
{
Console. WriteLine (title );
}

If you try to use the indexer to access an element but the transmitted key does not exist, an exception is thrown. The ContainsKey () method can be used to determine whether the passed key exists in the collection. TryGetValue this method tries to get the value of the specified key. If the value of the specified = key does not exist, this method will not throw an exception.

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.