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.

3
  • I'm going to guess the elegant answer involves Linq...you may want to add that tag. Commented Apr 22, 2015 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. Commented Apr 22, 2015 at 15:15
  • @TimSchmelter you are right, my bad. I've edited the example Commented Apr 22, 2015 at 17:37

1 Answer 1

5

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?

Sign up to request clarification or add additional context in comments.

3 Comments

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: 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.
I've ended up using the second solution. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.