How to sort two arrays by same index?

Use Array.Sort<TKey, TValue>(TKey[] keys, TValue[] items) that accepts two input arrays, one is the array of keys, the other is the array of items to sort using those keys. Here, for you, b is your keys and a is your items.

Thus:

Array.Sort(b, a);

will use the keys of b to sort the items of a.

I want to sort c by b‘s index -> c = {"1", "b", "u", "r", "a", "s"}

Not clear exactly what you mean. At the same time as you sort a using b? If so, it’s easy as we can still use the above. Zip a and c into a single array of Tuple<int, string>.

var d = a.Zip(c, (x, y) => Tuple.Create(x, y)).ToArray();

Then:

Array.Sort(b, d);

as above. Then extract the pieces:

a = d.Select(z => z.Item1).ToArray();
c = d.Select(z => z.Item2).ToArray();

Alternatively, if you need to sort a lot of arrays using the same set of keys:

int[] indexes = Enumerable.Range(0, b.Length).ToArray();
Array.Sort(b, indexes);

Now you can use indexes to sort all the arrays you need. For example:

a = indexes.Select(index => a[index]).ToArray();
c = indexes.Select(index => c[index]).ToArray();

etc. as needed.

Possibly some minor coding errors here. No compiler handy.

Leave a Comment