jaxxbo
jaxxbo

Reputation: 7464

Rearrange a list based on given order in c#

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?

Upvotes: 13

Views: 30950

Answers (2)

Li0liQ
Li0liQ

Reputation: 11254

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();

Upvotes: 34

Abe Miessler
Abe Miessler

Reputation: 85036

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]);
}

Upvotes: 9

Related Questions