2

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?

2
  • 3
    How can you have a 2d jagged array with those strings? They seems to be 3 field (of which 1 is integer) Commented Oct 27, 2011 at 15:14
  • It's an array of arrays... so myArray[0] = ["Apple", "2", "Bob"]; ie myArray[0, 0] is Apple, 0,1 is "2", etc. Commented Oct 27, 2011 at 15:30

3 Answers 3

7
var myOrderedRows = myArray.OrderBy(row => row[columnIndex]);
Sign up to request clarification or add additional context in comments.

6 Comments

It isn't an array at the end :-) It is an IOrderedEnumerable. Add a ToArray()
Are you satisfied if I rename the variable? ;)
Yep, same answer I was typing but was late to the party :-) data = data.OrderBy(sub => sub[columnIndex]).ToArray();
Sweet, thanks - I thought it was going to take a couple of hours to do this.
Even if you had to sort it manually - you need a 'couple of hours' to implement a bubblesort? ;p
|
3
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.

1 Comment

Thanks, this is useful to know
1

you can do like this...

IEnumerable<T> AsEnumerable(this T[,] arr) {
  for(int i = 0; i < arr.GetLength(0); i++)
    for(int j = 0; j < arr.GetLength(1); j++)
      yield return arr[i, j];
}

And then write for example:

int[,] data = // get data somwhere
// After 'AsEnumerable' you can use all standard LINQ operations
var res = data.AsEnumerable().OrderBy(n => n).Reverse();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.