# Sorting a Matrix

• ### Question

• User-1830403176 posted

Hi guys, i've this matrix:

3 1
10 1
30 1
41 1
10 4
21 4
30 4
10 7
10 10
30 10

i need to sort from the first coloumn.
This is what i should be obtained

3 1
10 1
10 4
10 7
10 10
21 4
30 1
30 4
30 10
41 1

i wrote this code:

```int[,] id = matrixPlusSort;
int[,] idcol = new int[matrixPlusSort.GetLength(0), matrixPlusSort.GetLength(1)];
int a;
int b;
int d;
for (int i = 0; i < matrixPlus.GetLength(0); i++)
{

a = id[i, 0];
d = id[i, 1];
b = i;
int b1 = i;
while ((b > 0) && (id[b - 1, 0] > a))
{
id[b, 0] = id[b - 1, 0];
b = b - 1;
}
id[b, 0] = a;
idcol[b, 1] = d;
idcol[b1, 1] = d;
}
int[,] id3 = new int[matrixPlusSort.GetLength(0), matrixPlusSort.GetLength(1)];
for (int i = 0; i < matrixPlus.GetLength(0); i++)
{
id3[i, 0] = id[i, 0];
id3[i, 1] = idcol[i, 1];
}```

With this code my output is:

3 1
10 1
10 4
10 7
10 10
21 4
30 4 *
30 7 *
30 10
41 10*

I marked with * rows that have the wrong value in the second column.

Can you help me understand what am I doing wrong?

Thanks!!!

Thursday, June 6, 2013 8:58 AM

• User-837620913 posted

Ugh, I wouldn't want to write that at all. Create a custom class to model your Matrix elements, like this:

```public class Matrix {
public int First {get;set;}
public int Second {get;set;}
}```

Then use LINQ to order them, like this:

`var sortedMatrix = yourListOfMatrixElements.OrderBy(x => x.First).ThenBy (x => x.Second).ToList();`

Full example is here:

```private void SomeMethod()
{
List<Matrix> list = new List<Matrix>();
list.Add( new Matrix() { First=10, Second = 5});
list.Add( new Matrix() { First=10, Second = 1});
list.Add( new Matrix() { First=30, Second = 10});
list.Add( new Matrix() { First=30, Second = 4});

var sortedMatrix = list.OrderBy(x => x.First).ThenBy (x => x.Second).ToList();

// do something with result here

}

public class Matrix {
public int First {get;set;}
public int Second {get;set;}
}

```

• Marked as answer by Thursday, October 7, 2021 12:00 AM
Friday, June 7, 2013 6:05 AM