3

我有一个字符串字典,整数所以键是字符串,值是整数,我想按整数值升序排列键。我怎么能做到这一点?

4

3 回答 3

13

您可以使用LINQ按值排序Dictionary

Dim dictionary = New Dictionary(Of String, Integer)() 
dictionary.Add("A", 2)
dictionary.Add("B", 4)
dictionary.Add("C", 5)
dictionary.Add("D", 3)
dictionary.Add("E", 1)

Dim sorted = From pair In dictionary
             Order By pair.Value
Dim sortedDictionary = sorted.ToDictionary(Function(p) p.Key, Function(p) p.Value)

实际上它不会修改原始字典,而是使用新顺序创建一个新字典。

但是:除了可行性之外, aDictionary不是一个IList(作为一个数组或List<T>)。它的目的是非常有效地查找密钥,但不是循环所有条目。

它们是无序的,这意味着尽管您可以使用 foreach 循环以某种顺序检索元素,但该顺序没有特殊含义,并且可能会无缘无故地更改。

于 2012-07-10T20:56:51.343 回答
4

首先,字典没有内在顺序。它用于查找。但是,您可以将键变成它们自己的有序列表。

Dim keyList as List(Of String) = (From tPair As KeyValuePair(Of String, Integer) _
                                  In myDictionary Order By tPair.Value Ascending _
                                  Select tPair.Key).ToList
于 2012-07-10T20:47:11.543 回答
3

我不得不对自定义对象做类似的事情。我认为这应该接近(但可能不完全是)您正在寻找的内容:

Dim sortedL As List(Of KeyValuePair(Of String, Integer)) = yourDictionary.ToList
sortedL.Sort(Function(firstPair As KeyValuePair(Of String, Integer), nextPair As KeyValuePair(Of String, Integer)) CInt(firstPair.Value).CompareTo(CInt(nextPair.Value)))
于 2012-07-10T20:46:30.577 回答