Click here to Skip to main content
Click here to Skip to main content

Sorting a Two-Dimensional Array in C#

By , 16 Mar 2011
 

I'm a fan of Linq and extension methods for things like this. So, how does this look to you?

public static class MultiDimensionalArrayExtensions
{
  /// <summary>
  ///   Orders the two dimensional array by the provided key in the key selector.
  /// </summary>
  /// <typeparam name="T">The type of the source two-dimensional array.</typeparam>
  /// <param name="source">The source two-dimensional array.</param>
  /// <param name="keySelector">The selector to retrieve the column to sort on.</param>
  /// <returns>A new two dimensional array sorted on the key.</returns>
  public static T[,] OrderBy<T>(this T[,] source, Func<T[], T> keySelector)
  {
      return source.ConvertToSingleDimension().OrderBy(keySelector).ConvertToMultiDimensional();
  }
  /// <summary>
  ///   Orders the two dimensional array by the provided key in the key selector in descending order.
  /// </summary>
  /// <typeparam name="T">The type of the source two-dimensional array.</typeparam>
  /// <param name="source">The source two-dimensional array.</param>
  /// <param name="keySelector">The selector to retrieve the column to sort on.</param>
  /// <returns>A new two dimensional array sorted on the key.</returns>
  public static T[,] OrderByDescending<T>(this T[,] source, Func<T[], T> keySelector)
  {
      return source.ConvertToSingleDimension().
      	OrderByDescending(keySelector).ConvertToMultiDimensional();
  }
  /// <summary>
  ///   Converts a two dimensional array to single dimensional array.
  /// </summary>
  /// <typeparam name="T">The type of the two dimensional array.</typeparam>
  /// <param name="source">The source two dimensional array.</param>
  /// <returns>The repackaged two dimensional array as a single dimension based on rows.</returns>
  private static IEnumerable<T[]> ConvertToSingleDimension<T>(this T[,] source)
  {
      T[] arRow;
 
      for (int row = 0; row < source.GetLength(0); ++row)
      {
          arRow = new T[source.GetLength(1)];
 
          for (int col = 0; col < source.GetLength(1); ++col)
              arRow[col] = source[row, col];
 
          yield return arRow;
      }
  }
  /// <summary>
  ///   Converts a collection of rows from a two dimensional array back into a two dimensional array.
  /// </summary>
  /// <typeparam name="T">The type of the two dimensional array.</typeparam>
  /// <param name="source">The source collection of rows to convert.</param>
  /// <returns>The two dimensional array.</returns>
  private static T[,] ConvertToMultiDimensional<T>(this IEnumerable<T[]> source)
  {
      T[,] twoDimensional;
      T[][] arrayOfArray;
      int numberofColumns;
 
      arrayOfArray = source.ToArray();
      numberofColumns = (arrayOfArray.Length > 0) ? arrayOfArray[0].Length : 0;
      twoDimensional = new T[arrayOfArray.Length, numberofColumns];
 
      for (int row = 0; row < arrayOfArray.GetLength(0); ++row)
          for (int col = 0; col < numberofColumns; ++col)
              twoDimensional[row, col] = arrayOfArray[row][col];
 
      return twoDimensional;
  }
}

Then, to be able to use the code above, you would simply do something like the following:

int[,] array = new int[3, 3] { { 1, 4, 2 }, { 4, 5, 1 }, { 7, 3, 8 } };
 
int[,] sortedByFirstElement = array.OrderBy(x => x[0]);
int[,] sortedBySecondElement = array.OrderBy(x => x[1]);
int[,] sortedByThirdElement = array.OrderBy(x => x[2]);

The keyselector Func is merely the way to determine the column to sort on using lambdas.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Andrew Rissing
Software Developer (Senior)
United States United States
Member
Since I've begun my profession as a software developer, I've learned one important fact - change is inevitable. Requirements change, code changes, and life changes.
 
So..If you're not moving forward, you're moving backwards.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralReason for my vote of 5 Elegant solution, though not as tran...memberDrABELL9 Apr '11 - 12:45 
Reason for my vote of 5
Elegant solution, though not as transparent as the original one. Also, performance comparison would be handy. 5*
GeneralI would like to see an example of how one would implement th...memberTony Zackin10 Mar '11 - 16:42 
I would like to see an example of how one would implement this, specifically the "keySelector" function. Your alternative, which might be more efficient, is certainly not as obvious nor straightforward as the one I have instantiated.
GeneralRe: While I haven't tested it for performance, it may very well ...memberAndrew Rissing11 Mar '11 - 4:14 
While I haven't tested it for performance, it may very well be more performat than relying on a DataTable to do the sorting, since it has to parse the string passed into the "Select" method. I mainly was trying to get away from having to pass the sort column as an integer and then the sorting direction as a string. Furthermore, using the above style is very much inline and natural for someone who is use to Linq's OrderBy extension methods.
 
Btw, I've updated my alternate to provide a more complete picture of what the code would be and an example of how to use it.
GeneralRe: Thanks for pointing out the extra ToArray. I have removed it...memberAndrew Rissing16 Mar '11 - 9:12 
Thanks for pointing out the extra ToArray. I have removed it, since it is not needed.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 16 Mar 2011
Article Copyright 2011 by Andrew Rissing
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid