Developers Planet

abhilash sukumari February 2016

Sort 2D array based on user provided indices

In python there is a functionality (numpy.take) to sort arrays within an array, for example if I have an array (3x3):

``````a = [[1, 2, 3],[7,9,10],[3, 5,6]]
``````

and I have an array of set indices

``````indices = [2, 0, 1]
``````

the result shall be

``````array([[ 3,  5,  6], [ 1,  2,  3], [ 7,  9, 10]]).
``````

Are there any direct approach methods/ functions as these in C# where I can pass in a jagged array and produce the same output?

juharr February 2016

Not directly, but you can achieve the same thing with Linq

``````var a = new[] { new[] { 1, 2, 3 }, new[] { 7, 9, 10 }, new[] { 3, 5, 6 } };
var indices = new [] { 2, 0, 1 };
var sorted = indices.Select(i => a[i]).ToArray();
foreach(var s in sorted) Console.WriteLine(string.Join(", ", s));
``````

Note this does not check that your indices are all in range.

Olivier Jacot-Descombes February 2016

You can do it easily with LINQ:

``````var a = new[] { new[] { 1, 2, 3 }, new[] { 7, 9, 10 }, new[] { 3, 5, 6 } };
var indices = new[] { 2, 0, 1};

var result = indices
.Select(i => a[i])
.ToArray();
``````

Or `.ToList()` if you prefer lists.

Szabolcs Dézsi February 2016

``````var a = new[]
{
new[] {1, 2, 3},
new[] {7, 9, 10},
new[] {3, 5, 6}
};

var indices = new[] {2, 0, 1};

var sortedArray = a.SortEx(indices);
``````

Where `SortEx` is

``````public static class Extensions
{
public static T[][] SortEx<T>(this T[][] source, int[] indices)
{
return indices.Select(index => source[index]).ToArray();
}
}
``````

This assumes that the all the indices in the `indices` array are not out of bound in `a`.

Teodor Ivanov February 2016

There is also the `Array.Sort(keys, values)` - MSDN