2

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.

kutas
  • 347
  • 3
  • 13
  • I'm going to guess the elegant answer involves Linq...you may want to add that tag. – Tim Apr 22 '15 at 14:55
  • The question is not clear because of the expected result. If the content of the `sortorder`-list specifies the value used for the sorting then item1=3,item2=1,item3=2. So the result should be(ascending): item2,item3,item1. – Tim Schmelter Apr 22 '15 at 15:15
  • @TimSchmelter you are right, my bad. I've edited the example – kutas Apr 22 '15 at 17:37

1 Answers1

4

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?

Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • actually there're many different collections and sometimes they are related, sometimes not. I was hoping to be able to perform the sort without merging the related collections. – kutas Apr 22 '15 at 17:45
  • @kutas: above does not really merge them. They are just linked in the query to lookup the sorting value via index. The original collections are not modified apart from the list that you want to sort. – Tim Schmelter Apr 22 '15 at 17:51
  • I've ended up using the second solution. Thanks! – kutas Apr 23 '15 at 09:37