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

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)