简体   繁体   中英

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. ie 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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM