13

I have a list as follows:

{CT, MA, VA, NY}

I submit this list to a function and I get the optimum waypoint order list

{2,0,1,3}

Now I have to rearrange the list as per the order that is newly provided. i.e. after rearranging, the list should look like:

{VA, CT, MA, NY}

What is the optimum way to do it? Using linq is there a way?

2
  • 6
    LINQ ALL THE THINGS!!!!11111ONEONE. But seriously, just because you are manipulating a list, does not mean you should use Linq. In fact, this one is simple enough that using Linq probably overcomplicates it
    – cadrell0
    May 15, 2013 at 18:27
  • 5
    @cadrell0, while your point is well taken, there is nothing complicated about the Linq on this one. May 15, 2013 at 18:28

2 Answers 2

33

You could try the following:

var list = new List<string>{"CT", "MA", "VA", "NY"};
var order = new List<int>{2, 0, 1, 3};
var result = order.Select(i => list[i]).ToList();
2
  • 4
    @weston The question clearly states that - no assumptions here :)
    – Li0liQ
    May 15, 2013 at 18:43
  • Awesome solution: just to clearify whats happening here: the list "order" sort of assigns a new order value to the old list in the order of the existing list. so basically stating that: CT now is 2, MA = 0, VA = 1 and NY = 3. Next we are cycling trough the existing list and selecting the items by its index with the new order. the final "toList()" then puts it back onto a list "result" which is the same exact list as before (even with many properties to the list) only in the desired order. its a very smart and quick solution.
    – inno
    Nov 4, 2022 at 11:23
8

This seems like the simplest approach:

oldItems = LoadItems(); //{"CT","MA","VA","NY"};
List<string> newItems = List<string>();
foreach(int idx in returnedIndexes)
{
   newItems.Add(oldItems[idx]);
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.