3

我有一本字典

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")
4

4 回答 4

12

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;
  }
}

要与 a 一起使用,SortedDictionary您唯一需要更改的是声明

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

其余代码可以保持不变

于 2013-03-27T19:26:48.607 回答
3

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

List<KeyValuePair<string, string>> results = rList.OrderByDescending(x => x.Key.Count(c => c == '/')).ToList();
于 2013-03-27T19:29:45.203 回答
1

试试这个:

 var result = rList.OrderBy(input => input.Key.Select(c => c == '/').Count()).Reverse().ToList();
于 2013-03-27T19:29:55.067 回答
0

来自 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();
}
于 2013-03-27T19:31:13.133 回答