vb.net 根据键对字典排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7825525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sort Dictionary based on keys
提问by user489041
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?
我需要根据键在 VB.net 中订购字典。键和值都是字符串。字典没有.Sort()
. 有没有办法在不必编写自己的排序算法的情况下做到这一点?
回答by LarsTech
SortedDictionarycomes to mind, but it sorts only on the key.
SortedDictionary 浮现在脑海中,但它只对键进行排序。
Otherwise, this answer might help How do you sort a C# dictionary by value?.
否则,这个答案可能会帮助你如何按值对 C# 字典进行排序?.
回答by Jim Wooley
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:
如果您需要保留底层字典而不使用 SortedDictionary,则可以使用 LINQ 根据您需要的条件返回 IEnumerable:
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.
SortedDictionary 可能会在重复使用的情况下提供更高的性能,但是只要您在将来的某个时候不需要反转该排序。
回答by apros
Exactly in vb.net work this code:
正是在 vb.net 中使用此代码:
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