If you need to sort the required collection based on keys, you can use the SortedList<TKey,TValue> class. This class sorts elements by key. The values and keys in this set can be of any type. Custom types defined as keys require the implementation of the IComparer<T> interface to sort elements in the list.
Use the constructor to create an ordered list, and add it using the Add method:
var books = new SortedList<string, string>(); ("Professional WPF Programming", "978–0–470–04180–2"); ("Professional 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>There are multiple overloaded versions of 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 contains the key and value:
foreach (KeyValuePair<string, string> book in books) { ("{0}, {1}", , ); }
The iterative statement will be displayed in the order of keys:
Beginning Visual C# 2010, 978–0–470-50226-6 Professional 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
Values and keys can also be accessed using the Values and Keys properties:
foreach (string isbn in ) { (isbn); } foreach (string title in ) { (title); }
If you try to access an element using an indexer, but the passed key does not exist, an exception will be thrown. The ContainsKey() method can determine whether the passed key exists in the set. TryGetValue This method tries to get the value of the specified key. If the value corresponding to the specified = key does not exist, the method will not throw an exception.
This is all about this article about the ordered list of C# collections. I hope it will be helpful to everyone's learning and I hope everyone will support me more.