If Dictionary stores a website page traffic, key is a web page The name and value correspond to the number of visits to the web page. Since the visits to the web page are continuously counted, int cannot be used as the key. Only the name of the web page can be used. The code for creating a Dictionary object and adding data is as follows :
Dictionary<string, int> dic = new Dictionary<string, int>(); dic.Add("index.html", 50); dic.Add("product.html", 13); dic.Add("aboutus.html", 4); dic.Add("online.aspx", 22); dic.Add("news.aspx", 18);
1. Dictionary sorting by value value
private void DictonarySort(Dictionary<string, int> dic) { var dicSort = from objDic in dic orderby objDic.Value descending select objDic; foreach(KeyValuePair<string, int> kvp in dicSort) Response.Write(kvp.Key + ":" + kvp.Value + "<br />"); }
Sorting results:
index.html:50
online.aspx:22
news.aspx:18
product.html:13
aboutus.html:4
The above code is in descending order (Reverse order). If you want to arrange in ascending order (order), you only need to remove the descending on the right side of variable dicSort.
2. C# dictionary key sorting
If you want to sort by Key, you only need to change the objDic.Value on the right side of the variable dicSort to objDic.Key.
1. Dictionary is sorted by value value (reverse order)
private void DictionarySort(Dictionary<string, int> dic) { if (dic.Count > 0) { List<KeyValuePair<string, int>> lst = new List<KeyValuePair<string, int>>(dic); lst.Sort(delegate(KeyValuePair<string, int> s1, KeyValuePair<string, int> s2) { return s2.Value.CompareTo(s1.Value); }); dic.Clear(); foreach (KeyValuePair<string, int> kvp in lst) Response.Write(kvp.Key + ":" + kvp.Value + "<br />"); } }
Sort results:
index.html: 50
online.aspx:22
news.aspx:18
product.html:13
aboutus.html:4
Sequential arrangement: just return the variable s2.Value .CompareTo(s1.Value); can be changed to return s1.Value.CompareTo(s2.Value);.
2. C# dictionary key sorting (reverse order, sequential order)
If you want to sort by Key, just change return s2.Value.CompareTo(s1.Value); to return s2.Key.CompareTo(s1.Key); in reverse order; just change return s2.Key.CompareTo in reverse order. (s1.Key); can be changed to return s1.Key.CompareTo(s2.Key);.
The above is the detailed content of Detailed explanation of the order and reverse order of Dictionary in C#. For more information, please follow other related articles on the PHP Chinese website!