C# dictionary Dictionary sorting (order, reverse order) notes

1. Create a Dictionary object
  If the Dictionary stores the traffic of a website page, the key is the name of the webpage, and the value corresponds to the number of times the webpage has been visited. Since the visits of the webpage are mainly for continuous statistics, int cannot be used as the key. You can only use the web page name, create a Dictionary object and add data code 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);

2. Dictionary sorting in versions above .net 3.5 (that is, linq dictionary sorting)
  1. Dictionary is sorted by 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 + “
”);
  }

Sort results:

index.html:50
  online.aspx:22
  news.aspx:18
  product.html:13
  aboutus.html:4

The above code is arranged 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 the variable dicSort.

2. C# dictionary key sorting

If you want to sort by Key, just change the objDic.Value on the right side of the variable dicSort to objDic.Key.

3. Dictionary sorting in .net 2.0 version
  1. Dictionary sorting by 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 + “
”);
    }
  }

Sort results:

index.html:50
  online.aspx:22
  news.aspx:18
  product.html:13
  aboutus.html:4

Sequential arrangement: Just change the variable return s2.Value.CompareTo(s1.Value); to return s1.Value.CompareTo(s2.Value);

2. C# dictionary key sorting (reverse order, order)

If you want to sort by Key, you only need to change return s2.Value.CompareTo(s1.Value); to return s2.Key.CompareTo(s1.Key); in reverse order; just change return s2.Key.CompareTo(s1. Key); Change to return s1.Key.CompareTo(s2.Key);

Guess you like

Origin blog.csdn.net/quailchivalrous/article/details/104185775