Sorting a dictionary by value with linq in vb.net

给你一囗甜甜゛ 提交于 2020-01-06 04:39:04

问题


I'm trying to sort a dictionary by value with LINQ but I can't figure how the ToDictionary() method works.

All the examples I can find are in c#.

here's my code

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

UPDATE

Finally, I just realized that was stupid. Sorry

I did a list (of keyValuePair(of string,string))

And to sort my list, I do

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

hope it will help someone


回答1:


You said you didn't find an example of this, but check MSDN here. Something like the following should work in 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)

But if you store a sorted enumerator in a dictionary again, it becomes unsorted, that's a property of a dictionary or map in general and is precisely why dictionaries are so fast and popular. If you need it sorted, perhaps you want to use SortedDictionary instead?




回答2:


Can your just use SortedDictionary?


Also in C# what you want to achieve would look like the following:

// 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);

what is the same to

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



回答3:


A dictionary does not make any guarantees about the order of the entries. I suggest You select the entries and convert it to a List of those KeyValuePairs:

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

Update: If you look at the documentation at MSDN, you will find that it explicitly states that "The order in which the items are returned is undefined". So really. Do not expect a Dictionary to be ordered.



来源:https://stackoverflow.com/questions/9841802/sorting-a-dictionary-by-value-with-linq-in-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!