How do I sort a two-dimensional (rectangular) array in C#?

112,697

Solution 1

Load your two-dimensional string array into an actual DataTable (System.Data.DataTable), and then use the DataTable object's Select() method to generate a sorted array of DataRow objects (or use a DataView for a similar effect).

// assumes stringdata[row, col] is your 2D string array
DataTable dt = new DataTable();
// assumes first row contains column names:
for (int col = 0; col < stringdata.GetLength(1); col++)
{
    dt.Columns.Add(stringdata[0, col]);
}
// load data from string array to data table:
for (rowindex = 1; rowindex < stringdata.GetLength(0); rowindex++)
{
    DataRow row = dt.NewRow();
    for (int col = 0; col < stringdata.GetLength(1); col++)
    {
        row[col] = stringdata[rowindex, col];
    }
    dt.Rows.Add(row);
}
// sort by third column:
DataRow[] sortedrows = dt.Select("", "3");
// sort by column name, descending:
sortedrows = dt.Select("", "COLUMN3 DESC");

You could also write your own method to sort a two-dimensional array. Both approaches would be useful learning experiences, but the DataTable approach would get you started on learning a better way of handling tables of data in a C# application.

Solution 2

Can I check - do you mean a rectangular array ([,])or a jagged array ([][])?

It is quite easy to sort a jagged array; I have a discussion on that here. Obviously in this case the Comparison<T> would involve a column instead of sorting by ordinal - but very similar.

Sorting a rectangular array is trickier... I'd probably be tempted to copy the data out into either a rectangular array or a List<T[]>, and sort there, then copy back.

Here's an example using a jagged array:

static void Main()
{  // could just as easily be string...
    int[][] data = new int[][] { 
        new int[] {1,2,3}, 
        new int[] {2,3,4}, 
        new int[] {2,4,1} 
    }; 
    Sort<int>(data, 2); 
} 
private static void Sort<T>(T[][] data, int col) 
{ 
    Comparer<T> comparer = Comparer<T>.Default;
    Array.Sort<T[]>(data, (x,y) => comparer.Compare(x[col],y[col])); 
} 

For working with a rectangular array... well, here is some code to swap between the two on the fly...

static T[][] ToJagged<T>(this T[,] array) {
    int height = array.GetLength(0), width = array.GetLength(1);
    T[][] jagged = new T[height][];

    for (int i = 0; i < height; i++)
    {
        T[] row = new T[width];
        for (int j = 0; j < width; j++)
        {
            row[j] = array[i, j];
        }
        jagged[i] = row;
    }
    return jagged;
}
static T[,] ToRectangular<T>(this T[][] array)
{
    int height = array.Length, width = array[0].Length;
    T[,] rect = new T[height, width];
    for (int i = 0; i < height; i++)
    {
        T[] row = array[i];
        for (int j = 0; j < width; j++)
        {
            rect[i, j] = row[j];
        }
    }
    return rect;
}
// fill an existing rectangular array from a jagged array
static void WriteRows<T>(this T[,] array, params T[][] rows)
{
    for (int i = 0; i < rows.Length; i++)
    {
        T[] row = rows[i];
        for (int j = 0; j < row.Length; j++)
        {
            array[i, j] = row[j];
        }
    }
}

Solution 3

Array.Sort(array, (a, b) => { return a[0] - b[0]; });

Solution 4

Here is an archived article from Jim Mischel at InformIt that handles sorting for both rectangular and jagged multi-dimensional arrays.

Solution 5

Can allso look at Array.Sort Method http://msdn.microsoft.com/en-us/library/aa311213(v=vs.71).aspx

e.g. Array.Sort(array, delegate(object[] x, object[] y){ return (x[ i ] as IComparable).CompareTo(y[ i ]);});

from http://channel9.msdn.com/forums/Coffeehouse/189171-Sorting-Two-Dimensional-Arrays-in-C/

Share:
112,697
Jack
Author by

Jack

Updated on January 08, 2022

Comments

  • Jack
    Jack over 2 years

    I have a two-dimensional array (of Strings) which make up my data table (of rows and columns). I want to sort this array by any column. I tried to find an algorithm for doing this in C#, but have not been successful.

    Any help is appreciated.

  • Marc Gravell
    Marc Gravell over 15 years
    That example doesn't actually sort the array; the LINQ will produce a sorted sequence, but only if you capture the result... it doesn't sort the existing array. This could just be: string[] names = {"Smith","Snyder","Baker","Jonson","Ballmer"}; Array.Sort(names);
  • Doug L.
    Doug L. over 15 years
    I can see what you're saying - I'll remove the flawed example, but leave in the link to the sorting article. PS - thank you for telling me the reason for the down vote. You don't see that often but it truely IS constructive!
  • Jack
    Jack over 15 years
    That sounds interesting, can you post or link to some code examples please.
  • MusiGenesis
    MusiGenesis over 15 years
    Done. It might have a bug somewhere - I wrote it in notepad.
  • Jack
    Jack over 15 years
    Amazed you wrote that in notepad - at any rate, it worked very well. Thank you.
  • KFL
    KFL over 6 years
    Link is broken. It redirects to the website's homepage
  • Doug L.
    Doug L. over 6 years
    Thank you KFL, I edited the link to point to an archived version. As much as I would prefer to link to a current version on the InformIT site for them, I can not easily find that content. It seems to have been removed.
  • Homam
    Homam over 5 years
    What changes needs to be done in Sort method to sort data in descending mode.
  • Marc Gravell
    Marc Gravell over 5 years
    @Homam comparer.Compare(y[col],x[col])) (reverse x and y there)
  • Korashen
    Korashen over 4 years
    Welcome to SO. Please do not post code only answers. As the code is simple to you, others might struggle to understand it and why you used that approach. Please elaborate on your code why you did it that way. Also, please notice that this question is from 2008.
  • Job_September_2020
    Job_September_2020 about 3 years
    @Korashen: You got a good suggestion. Would you please tell me if that line of code will first sort the whole array by the first index, and then next will sort the whole array by the second index of the array ? Does this require "using System.Linq" ? Thanks.
  • Job_September_2020
    Job_September_2020 about 3 years
    Hi No_Nick, if I have a 2 dimensional array, and I want do 2 sorting on this array at the same time : (1) First, sort by the first index; (2) Next for all elements that have the same values for the first index, please sort them by the second index; -- Would you please tell me how to do that with Array.Sort() as you wrote ? Thank you.