Reorder the list according to the given order in C #

I have a list:

{CT, MA, VA, NY} 

I pass this list to a function and get a list of optimal waypoints

 {2,0,1,3} 

Now I need to rearrange the list according to the order that was recently provided. those. after rearrangement, the list should look like this:

 {VA, CT, MA, NY} 

What is the best way to do this? Is there a way using linq?

+6
source share
2 answers

You can 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(); 
+19
source

This seems like the easiest way:

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

Source: https://habr.com/ru/post/945093/


All Articles