kutas
kutas

Reputation: 377

VB.NET: sorting list by another list

How to sort somelist As List(of T) by the order set in another list sortorder As List(of Integer)? Both somelist and sortorder are of the same size and are indexed from 0 to n. Integers in the sortorder list determine the sort order: new index of item X in somelist = value of item X in sortorder.

Like this:

somelist = (itemA, itemB, itemC)
sortorder = (3, 1, 2)
somelist.sort()
somelist = (itemB, itemC, itemA)

I am trying to sort several equally sized lists using the predefined sort order.

Upvotes: 2

Views: 1850

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460168

You could use LINQ, although i hate the ugly method syntax in VB.NET:

somelist = somelist.
    Select(Function(t, index) New With {.Obj = t, .Index = index}).
    OrderBy(Function(x) sortorder(x.Index)).
    Select(Function(x) x.Obj).
    ToList()

This uses the overload of Enumerable.Select that projects the index of the item. The object and the index are stored in an anonymous type which is used for the ordering, finally i'm selecting the object and use ToList to build the ordered list.

Another way is to use Enumerable.Zip to merge both into an anonymous type:

Dim q = From x In somelist.Zip(sortorder, Function(t, sort) New With {.Obj = t, .Sort = sort})
        Order By x.Sort Ascending
        Select x.Obj 
somelist = q.ToList()

If you want to order it descending, so the highest values first, use OrderByDescending in the method syntax and Order By x.Sort Descending in the query.

But why do you store such related informations in two different collections at all?

Upvotes: 5

Related Questions