VB.net,如何按值对集合项进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16923301/
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
VB.net, How to sort collection items by value
提问by exim
How do I sort collection items by value in VB.NET?
如何在 VB.NET 中按值对集合项进行排序?
I want to sort this:
我想这样排序:
Dim col as Collection = New Collection
col.Add("b","b1")
col.Add("a","a1")
col.Add("d","d1")
回答by KyleMit
Like @Krishnadditya mentioned, Collections aren't ideal for sorting because they contain items of type Objectwhich is too genereic to be useful in comparing against each other. If you weren't married to a collection, you can do this with a LINQ query to a list or anything that can be cast an enumerable
就像@Krishnadditya 提到的那样,集合不是排序的理想选择,因为它们包含的项目类型Object过于通用而无法相互比较。如果您没有与集合结婚,则可以使用 LINQ 查询列表或任何可以转换为可枚举的内容来执行此操作
Dim list = {
New With {.Object = "b", .Key = "b1"},
New With {.Object = "a", .Key = "a1"},
New With {.Object = "d", .Key = "d1"}}
Dim sortedList = _
From item In list
Order By item.Key
回答by exim
I decide to use dictionary:
我决定使用字典:
Dim newcol = (From entry In col
Order By entry.Value Descending).ToDictionary(
Function(pair) pair.Key,
Function(pair) pair.Value)
回答by krishnaaditya
As Collection.Addtakes general object type and no specific type - sort is not possible. As objects need to be compared against each other to be sort, it will be like comparing oranges and apples.
由于Collection.Add采用通用对象类型而没有特定类型 - 排序是不可能的。由于对象需要相互比较才能进行排序,就像比较橙子和苹果一样。
And Collection provides sorting by Key and not value.
并且 Collection 提供按键而不是值排序。
I think, you may have to extend the Collection class and implement the sort. you can move the items by using Insertand RemoveAtmethods.
我认为,您可能需要扩展 Collection 类并实现排序。您可以使用Insert和RemoveAt方法移动项目。
And Just a thought/advice: if the values are of specific type, how about using some other data structure. Like dictionary for which you can sort by value as mentioned in this link
只是一个想法/建议:如果值是特定类型的,那么使用其他一些数据结构如何。就像字典一样,您可以按此链接中提到的值对其进行排序

