简体   繁体   中英

Sorting two dimensional array by columns in C#

I want to sort two-dimensional array. Instead of ordering for the first dimension I want to order the inner dimension.

For example if initial array is like this:

{{4, 1, 3},
{6, 5, 2},
{0, 9, 8}}

Then if we sort array by first row, result will be:

{{1, 3, 4},
{5, 2, 6},
{9, 8, 0}}

I managed doing this by transposing the array, ordering and transposing again. But is there a better way to do it?

If you can allow to use Linq , the easiest way is the following:

  • First add namespace using System.Linq;

  • Sorting: Array.ForEach(myArray, row => Array.Sort(row));

This will iterate over rows and sort by ascending.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM