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.