C# Sort list while also returning the original index positions?

.net, c#, collections, sorting

Solution

It can be done quite easily using Linq.

- Convert your list into a new list of pairs (object, original index of object).

- Sort the new list by the first item in the pair

- Extract the sorted list and the original indices.

Here's some code to demonstrate the principle:

List<int> A = new List<int>() { 3, 2, 1 };

var sorted = A
    .Select((x, i) => new KeyValuePair<int, int>(x, i))
    .OrderBy(x => x.Key)
    .ToList();

List<int> B = sorted.Select(x => x.Key).ToList();
List<int> idx = sorted.Select(x => x.Value).ToList();

I think this gives A[idx[i]] = B[i], but that hopefully is good enough for you.

Problem

I'm interested in sorting a collection, but also returning an index which can be used to map to the original position in the collection (before the sort). Let me give an example to be more clear: ``` List<int> A = new List<int>(){3,2,1}; List<int> B; List<int> idx; Sort(A,out B,out idx); ``` After which: ``` A = [3,2,1] B = [1,2,3] idx = [2,1,0] ``` So that the relationship between A,B,idx is: `A[i] == B[ idx[i] ]` , for i = 0...2 Does C#/.Net have any built in mechanism to make this easy to implement? Thanks.

Original source