0

Whats wrong with this code?

I'm using System.Linq

int[,] array = new int[3, 3] { { 1, 4, 2 },
                               { 4, 5, 1 },
                               { 7, 3, 8 } 
                             };

int[,] sortedByFirst = array.OrderBy(x => x[0]);
int[,] sortedBySecond = array.OrderBy(x => x[1]);
int[,] sortedByThird = array.OrderBy(x => x[2]);

Error:

Are you missing a using directive or an assembly reference?

Dovydas Šopa
  • 2,282
  • 8
  • 26
  • 34

3 Answers3

2

2D Arrays don't work well with LINQ. What do you expect OrderBy to receive and sort, even if it were implemented on an n-dimensional array?

Much better to work with List.

var src = new List<int[]> { new[] { 1, 4, 2 },
                  new[] { 4, 5, 1 },
                  new[] { 7, 3, 8 } 
                };

var sortedByFirst = src.OrderBy(x => x[0]).ToList();
var sortedBySecond = src.OrderBy(x => x[1]).ToList();
var sortedByThird = src.OrderBy(x => x[2]).ToList();
NetMage
  • 26,163
  • 3
  • 34
  • 55
1

2D Arrays don't work with OrderBy. Feel free to try this:

 for (int i = 0; i < array.Length - 1; ++i)
                    {
                        for (int j = i; j < array.GetLength(0); ++j)
                        {
                           // for first column

                           int a = array[i,0]; // this way you can choose column whatever you want
                            int b = array[j,0];

                            if (a < b) 
                            {

                                for (int x = 0; x < array.GetLength(1); ++x)
                                {
                                    string temp = array[i, x];
                                    array[i, x] = array[j, x];
                                    array[j, x] = temp;
                                }
                            }

                        }
                    }
0

There is ambiguity about what you're trying to achieve. Are you looking to keep the "grid rows" in sync with each other when you sort by one of the "columns"? Or are you expecting to just have the values from a single "column" returned in order, separately from the other "columns"?

If it's the first, then I'd recommend following this example from another question similar to this one, and leverage the DataTable class to keep your rows from getting mixed up.

If it's the second, then you can just order the column via array[0].OrderBy(x=>x);

btw, I think with your code...

        int[,] ordered = array.OrderBy(x => x[0]).ToArray();

...that you were looking to use the int[][] type array, not the int[,] type array. The OrderBy exists for the other one, but it doesn't do what you're expecting I don't think. I've just tried it and I can't figure out what it's even doing.

Hope this helps!

Dan Rayson
  • 1,315
  • 1
  • 14
  • 37