Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort a 2d array using Linq?

Tags:

c#

linq

I have a 2d array of strings

string [] [] myArray;

and I want to sort it by one of the columns.

So the data might be

{ "Apple", "2", "Bob" },
{ "Banana", "1", "Fred" }

And I want to sort it by any of those columns - I'll have an index.

Ideally, I'd like to do something like myArray.Sort(1);

I understand I may have to use a custom comparer. I see this as an interesting learning opportunity. Can anyone offer some advice?

like image 921
NibblyPig Avatar asked Apr 20 '26 20:04

NibblyPig


2 Answers

var myOrderedRows = myArray.OrderBy(row => row[columnIndex]);
like image 145
fjdumont Avatar answered Apr 22 '26 08:04

fjdumont


Array.Sort(myArray, (p, q) => p[0].CompareTo(q[0]));

This will order the array in place (so at the end myArray will be sorted). LINQ OrderBy by comparison creates a new ordered enumerable that then you can convert to a ToArray.

like image 31
xanatos Avatar answered Apr 22 '26 08:04

xanatos