How do I sort a two-dimensional (rectangular) array in C#?
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.
How to sort a 2 dimensional array (jagged) by column
I found an answer posted where someone had asked a similar question but about rectangular arrays. This is a nice little method using Array.Sort with a lambda expression:
Array.Sort(contests, (a, b) => { return a[0] - b[0]; });
Which will sort a 2D array by the first column and keep the corresponding data in the second column (like sort rows by ID). If any row has the same value on the left side but different values on the right, then it will sort by value in the second column within those rows.
If you enter a 1 for the first value then it will sort by the right column:
Array.Sort(contests, (a, b) => { return a[1] - b[0]; });
How to Sort 2D Array in C#
You are using a 2D array to represent 2 separate vectors - the symbols and the counts. Instead, use 2 separate arrays. Array.Sort has an overload that takes 2 arrays, and sorts on one array, but applies the changes to both, achieving what you want.
This would also allow you to use a char[] for the characters rather than int[]:
char[] symbols = ...
int[] counts = ...
...load the data...
Array.Sort(counts, symbols);
// all done!
At this
point, the counts have been ordered, and the symbols will still match index-by-index with the count they relate to.
C# sorting multidimensional array by multiple columns
Use a List<> object with Linq
using System;using System.Collections.Generic;using System.Linq;using System.Text;
namespace ConsoleApplication19{ class Program { static void Main(string[] args) { List<List<int>> multiarray = new List<List<int>>{ new List<int> { 8, 63 }, new List<int> { 4, 2 }, new List<int> { 0, -55 }, new List<int> { 8, 57 }, new List<int> { 2, -120}, new List<int> { 8, 53 } };
List<List<int>> sortedList = multiarray.OrderBy(x => x[1]).OrderBy(y => y[0]).ToList();
} }}
C# - sorting a rectangular array by selected columns
In a multidimensional array, there isn’t really a concept of “rows”. All values are just in the same relation to another. That’s why sorting multidimensional arrays is somewhat tricky.
It gets easier when you use jagged arrays, basically arrays of arrays. Your array would look like this:
int[][] myJaggedArray = new int[][]
{
new int[] { 1, 7, 0, 0 },
new int[] { 2, 12, 0, 0 },
new int[] { 3, 15, 0, 0 },
new int[] { 4, 7, 0, 0 },
new int[] { 5, 1, 0, 0 },
};
You can also convert your multidimensional array into a jagged array, doing something like this:
int[][] myJaggedArray = new int[myArray.GetUpperBound(0) + 1][];
for(int i = 0; i < myJaggedArray.Length; i++)
myJaggedArray[i] = Enumerable.Range(0, myArray.GetUpperBound(1) + 1).Select(k => myArray[i,k]).ToArray();
Once you have a jagged array, sorting it is really easy using LINQ:
var result = myJaggedArray
.OrderBy(row => row[1])
.ThenBy(row => row[0])
.Select((row, idx) =>
{
row[2] = idx;
return row;
})
.ToArray();
Sort 2d array rows in ascending order of their first elements in c#
Sadly with that sintax you are missing the power of linq
wich is one of the best components of .Net framework
you can try this instead
double[][] x = new double[2][];
x[0] = new double[] { 5, 2, 5 };
x[1] = new double[] { 6, 8, 3 };
x[2] = new double[] { 8, 3, 6 };
var sortedByFisrtVal = x.OrderBy(y => y[0]);
var sortedBySecondVal = x.OrderBy(y => y[1]);
//trying to guess maybe this is better
var sorted = x.OrderBy(y => y[0]).ThenBy(y => y[1]).ThenBy(y => y[2]);
Related Topics
Java Equivalents of C# String.Format() and String.Join()
What Are Major Differences Between C# and Java
Difference Between Namespace in C# and Package in Java
Does Java Have Something Similar to C# Properties
How to Read a .Net Guid into a Java Uuid
What Is the "Volatile" Keyword Used For
How to Lock a Table on Read, Using Entity Framework
How to Use the Cancellationtoken Property
How to Get Ascii Value of String in C#
Order of Serialized Fields Using JSON.Net
Closing Excel Application Process in C# After Data Access
What Setup Code Should Go in Form Constructors Versus Form Load Event
Webexception How to Get Whole Response with a Body
Add "Everyone" Privilege to Folder Using C#.Net
Are Static Methods Thread Safe