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?
var myOrderedRows = myArray.OrderBy(row => row[columnIndex]);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With