【问题标题】:Sorting in Dictionary C#在字典 C# 中排序
【发布时间】:2013-03-27 19:25:10
【问题描述】:

我有一本字典

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

【问题讨论】:

标签: c# asp.net .net vb.net


【解决方案1】:

Dictionary&lt;TKey, TValue&gt; 类型是 .Net 中的无序集合。如果您想订购,则需要改用 SortedDictionary&lt;TKey, TValue&gt; 并提供自定义 IComparer&lt;string&gt; 来计算字符串中的 / 值。

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 ,您能否提供一个示例代码来使用 SortedDictionary 。
【解决方案2】:

JaredPar 已回答 Dictionary&lt;TKey, TValue&gt; 内容没有指定顺序。但是,您可以按所需顺序获得List&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;

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

【讨论】:

    【解决方案3】:

    试试这个:

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

    【讨论】:

    • 这行不通。这里的最终产品是Dictionary&lt;Tkey, TValue&gt;,它始终是无序的。 OP 想要一个有序值
    • 只要它以ToDictionary 调用结束,它就会出错。 Dictionary总是是无序的。将值添加到字典中的顺序无关紧要。他们被允许在枚举期间以不同的方式返回
    【解决方案4】:

    来自 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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-16
      • 2015-05-06
      • 1970-01-01
      • 1970-01-01
      • 2016-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多