Reputation: 626
How do I sort collection items by value in 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")
Upvotes: 3
Views: 14923
Reputation: 626
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)
Upvotes: 0
Reputation: 29909
Like @Krishnadditya mentioned, Collections aren't ideal for sorting because they contain items of type Object
which 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
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
Upvotes: 2
Reputation: 860
As Collection.Add takes 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.
And Collection provides sorting by Key and not value.
I think, you may have to extend the Collection class and implement the sort. you can move the items by using Insert and RemoveAt methods.
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
Upvotes: 0