Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 413
jaxxbo Avatar asked May 15 '13 18:05

jaxxbo


People also ask

How do you sort a list according to another list?

Approach : Zip the two lists. Create a new, sorted list based on the zip using sorted(). Using a list comprehension extract the first elements of each pair from the sorted, zipped list.

How do you rearrange elements in an array?

Approach(Naive Approach): Navigate the numbers from 0 to n-1. Now navigate through array. If (i==a[j]) , then replace the element at i position with a[j] position. If there is any element in which -1 is used instead of the number then it will be replaced automatically.


2 Answers

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();
like image 167
Li0liQ Avatar answered Sep 21 '22 04:09

Li0liQ


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]);
}
like image 38
Abe Miessler Avatar answered Sep 22 '22 04:09

Abe Miessler