I need to order a Dictionary in VB.net based off of the keys. The keys and values are all strings. The dictionary does not have a .Sort()
. Is there a way to do this without having to write my own sorting algorithm?
Asked
Active
Viewed 3.4k times
9

nawfal
- 70,104
- 56
- 326
- 368

user489041
- 27,916
- 55
- 135
- 204
-
What does "order a dictionary" mean to you? – jason Oct 19 '11 at 17:40
-
I modified it to clarify that, but it was edited. I need to order the dictionary based off of they keys. – user489041 Oct 19 '11 at 17:43
-
No, see, you still didn't say what you mean by "order a dictionary." Telling me that you want it based off of the keys doesn't explain what it means to you to "order a dictionary." – jason Oct 19 '11 at 17:48
-
1@Jason I think that it is apparent that "order a dictionary" to me, in the context of this question, means I want to sort it. – user489041 Oct 19 '11 at 21:45
-
1What does it to "sort" a dictionary to you? Do you want to mutate the dictionary in some way so that it's "sorted?" Do you want to produce just an ordering of the keys? Do you want to produce an ordering of the values? Do you want to produce an ordering of the key/value pairs? Do you want to produce an entirely new data structure that encapsulates the "sorting?" You see, you have the dictionary. The concept of "ordering" it is rather ambiguous, especially since the `Dictionary
` structure in .NET doesn't preserve any ordering whatsoever. – jason Oct 19 '11 at 22:36
3 Answers
19
SortedDictionary comes to mind, but it sorts only on the key.
Otherwise, this answer might help How do you sort a C# dictionary by value?.
5
Exactly in vb.net work this code:
Dim myDict As New Dictionary(Of String, String)
myDict.Add("one", 1)
myDict.Add("four", 4)
myDict.Add("two", 2)
myDict.Add("three", 3)
Dim sortedDict = (From entry In myDict Order By entry.Value Ascending).ToDictionary(Function(pair) pair.Key, Function(pair) pair.Value)
For Each entry As KeyValuePair(Of String, String) In sortedDict
Console.WriteLine(String.Format("{0,10} {1,10}", entry.Key, entry.Value))
Next

apros
- 2,848
- 3
- 27
- 31
-
I think you wanted `Order By entry.Key` not `entry.Value` based on the OP's edits. – Jim Wooley Oct 19 '11 at 18:06
-
4
If you need to retain the underlying Dictionary and not use a SortedDictionary, you could use LINQ to return an IEnumerable based off of what ever criteria you need:
Dim sorted = From item In items
Order By item.Key
Select item.Value
The SortedDictionary would probably give more performance under repeated usage however as long as you didn't need to invert that sort at some point in the future.

Jim Wooley
- 10,169
- 1
- 25
- 43