【问题标题】:Sorting a dictionary by value with linq in vb.net在 vb.net 中使用 linq 按值对字典进行排序
【发布时间】:2012-03-23 15:19:40
【问题描述】:

我正在尝试使用 LINQ 按值对字典进行排序,但我不知道 ToDictionary() 方法是如何工作的。

我能找到的所有例子都在 c# 中。

这是我的代码

Dim f As Dictionary(Of String, String) =  (From value In projectDescriptions.Values
                                           Order By value Ascending
                                           Select value).ToDictionary(???)

更新

最后,我才意识到这很愚蠢。对不起

我做了一个列表(keyValuePair(of string,string))

为了对我的列表进行排序,我会这样做

mylist.OrderBy(Function(x) x.Value).ToList()

希望对某人有所帮助

【问题讨论】:

    标签: .net vb.net linq sorting dictionary


    【解决方案1】:

    您说您没有找到这方面的示例,但请查看MSDN here。像下面这样的东西应该在 VB 中工作。

    'not sure what the key is, but use whichever property you'd like
    Dim f As Dictionary(Of String, String) =  
          (From value In projectDescriptions.Values
          Order By value Ascending
          Select value).ToDictionary(Function(p) p.Key)
    

    但是,如果您再次将已排序的枚举数存储在字典中,它就会变为未排序,这通常是字典或映射的属性,这正是字典如此快速和流行的原因。如果您需要对其进行排序,也许您想改用SortedDictionary

    【讨论】:

    • 你说得对,我才意识到我的问题有多愚蠢。对不起
    【解决方案2】:

    你可以使用SortedDictionary吗?


    在 C# 中,您想要实现的内容如下所示:

    // enumerate dic itself, not just dic.Values
    (from p in dic
    orderby p.Value ascending
    select new KeyValuePair<string, string>(p.Key, p.Value)
     // or new { Key = p.Key, Value = p.Value })
        .ToDictionary(p => p.Key, p => p.Value);
    

    有什么相同的

    dic.OrderBy(p => p.Value).ToDictionary(p => p.Key, p => p.Value);
                       // or .ToDictionary(p => p.Key);
    

    【讨论】:

      【解决方案3】:

      字典不保证条目的顺序。我建议您选择条目并将其转换为这些 KeyValuePairs 的列表:

      Dim f = projectDescriptions.OrderBy(Function(p) p.Value).ToList()
      

      更新:如果您查看the documentation at MSDN,您会发现它明确指出“返回项目的顺序未定义”。所以真的。 不要期望字典被订购。

      【讨论】:

      • 你会得到List&lt;KeyValuePair&lt;string, string&gt;&gt;而不是Dictionary&lt;string, string&gt;
      • 为什么这个答案被否决了? Botz 是对的,Dictionary 的顺序无法保证,因此按值对字典进行排序是没有意义的。
      • @abatishchev 不正是他所建议的吗?见博茨的文字。
      • @Meta-Knight:是的,不保证订单。但是你可以通过排序来保证。在新插入之前,我认为顺序将保持不变。
      • @Down:那显然是 C# 而不是 VB.NET
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-19
      相关资源
      最近更新 更多