字典中的排序

本文关键字:排序 字典 | 更新日期: 2023-09-27 18:06:15

我有一本字典

Dictionary<string, string> rList = new Dictionary<string, string>();
rList .Add("/a/b/c", "35");
rList .Add("/a/c/f/v", "25");
rList .Add("/a/r/d/c/r/v", "29");
rList .Add("/a", "21");
rList .Add("/a/f, "84");

我只想根据键中"/"的个数对这个字典进行排序。我的期望输出是,

("/a/r/d/c/r/v", "29")
("/a/c/f/v", "25")
("/a/b/c", "35")
("/a/f, "84")
("/a", "21")

字典中的排序

Dictionary<TKey, TValue>类型是。net中的无序集合。如果你想排序,那么你需要使用SortedDictionary<TKey, TValue>代替,并提供一个自定义的IComparer<string>来计算字符串中的/值。

sealed class SlashComparer : IComparer<string> { 
  static int CountSlashes(string str) { 
    if (String.IsNullOrEmpty(str)) { 
      return 0;
    }
    int count = 0;
    for (int i = 0; i < str.Length; i++) {
      if (str[i] == '/') {
         count++;
      }
    }
    return count;
  }
  public int Compare(string left, string right) { 
    int leftCount = CountSlashes(left);
    int rightCount = CountSlashes(right);
    return rightCount - leftCount;
  }
}

SortedDictionary一起使用,你唯一需要改变的是声明

var comparer = new SlashComparer();
var rList = new SortedDictionary<string, string>(comparer);

其余代码保持不变

JaredPar已经回答了Dictionary<TKey, TValue>内容没有指定顺序。但是,您可以获得具有所需顺序的List<KeyValuePair<TKey, TValue>>:

List<KeyValuePair<string, string>> results = rList.OrderByDescending(x => x.Key.Count(c => c == '/')).ToList();

试试这个:

 var result = rList.OrderBy(input => input.Key.Select(c => c == '/').Count()).Reverse().ToList();

from linqpad:

void Main()
{
    Dictionary<string, string> rList = new Dictionary<string, string>();
    rList .Add("/a/b/c", "35");
    rList .Add("/a/c/f/v", "25");
    rList .Add("/a/r/d/c/r/v", "29");
    rList .Add("/a", "21");
    rList .Add("/a/f", "84");
    var x = from a in rList
        let i = a.Key.ToCharArray().Count (k => k.Equals('/') )
        orderby i descending
        select a;
    x.Dump();
}