Marc
Marc

Reputation: 16512

Sorting a dictionary by value with linq in vb.net

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

Upvotes: 1

Views: 8283

Answers (3)

abatishchev
abatishchev

Reputation: 100288

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

Upvotes: 3

Botz3000
Botz3000

Reputation: 39620

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.

Upvotes: 1

Abel
Abel

Reputation: 57169

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?

Upvotes: 3

Related Questions