简体   繁体   English

VB.Net按整数的值排序字典(字符串,整数)

[英]VB.Net Order a Dictionary(Of String, Integer) by value of the Integer

I have a dictionary of String, Integer so the key is the string and the value is the integer and i want to order the keys ascending by the value of the integer. 我有一个String,Integer的字典,所以键是字符串,值是整数,我想按顺序对整数的值进行排序。 How could I achieve this? 我怎么能实现这个目标?

You could use LINQ to sort the Dictionary by value: 您可以使用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)

Actually it does not modify the original Dictionary but creates a new Dictionary with the new order. 实际上,它不会修改原始词典,而是使用新订单创建新词典。

But : Apart from the feasability, a Dictionary is not an IList (as an Array or List<T> ). 但是 :除了可行性之外, Dictionary不是IList (作为Array或List<T> )。 It's purpose is to lookup a key very efficiently but not to loop all entries. 它的目的是非常有效地查找密钥,但不循环所有条目。

They are unordered, meaning that although you can retrieve the elements in some order with a foreach loop, that order has no special meaning, and it might change for no apparent reason. 它们是无序的,这意味着尽管您可以使用foreach循环以某种顺序检索元素,但该顺序没有特殊含义,并且它可能会在没有明显原因的情况下发生变化。

First of all, a dictionary does not have an intrinsic order. 首先,字典没有内在的顺序。 It is for look-ups. 这是为了查找。 However, you can turn the keys into their own ordered list. 但是,您可以将密钥转换为自己的有序列表。

Dim keyList as List(Of String) = (From tPair As KeyValuePair(Of String, Integer) _
                                  In myDictionary Order By tPair.Value Ascending _
                                  Select tPair.Key).ToList

I had to do something similar to this with custom objects. 我必须使用自定义对象做类似的事情。 I think this should be close (but may not be exactly) what you're looking for: 我认为这应该接近(但可能不完全)你正在寻找的东西:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM