Reputation: 115
I have the array of integers: d[]. for example(7 columns and some rows):
4 1 8 0 3 2 6
7 0 4 9 1 1 5
0 6 1 3 5 2 0
and so on. At compile time I do not know how many columns has array d. And I do not know at compile time which columns to use to orderby.
For example need to sort by: d[5], d[2], d[0], d[3]. But at run time I know order of the columns to sort. For example column indexes: 5, 2, 0, 3 which mean d[5], d[2], d[0], d[3] columns. How can I orderby array d using this indexes of columns?
Upvotes: 1
Views: 1354
Reputation: 1062745
Assuming you are using a jagged array (int[][]
), then you can use LINQ by combining OrderBy
and ThenBy
:
using System;
using System.Collections.Generic;
using System.Linq;
static class Program
{
static void Main()
{
int[][] data = {
new[]{4,1,8,0,3,2,6},
new[]{7,0,4,9,1,1,5},
new[]{0,6,1,3,5,2,0}};
int[] sortCols = { 5, 2, 0, 3 };
IEnumerable<int[]> qry = data;
if (sortCols.Length > 0)
{
IOrderedEnumerable<int[]> sorted =
qry.OrderBy(row => row[sortCols[0]]);
for (int i = 1; i < sortCols.Length; i++)
{
int col = sortCols[i]; // for capture
sorted = sorted.ThenBy(row => row[col]);
}
qry = sorted;
}
// show results (does actual sort when we enumerate)
foreach (int[] row in qry)
{
foreach (int cell in row)
{
Console.Write(cell);
Console.Write('\t');
}
Console.WriteLine();
}
}
}
You could also (alternatively) build a comparison to pass to Array.Sort
.
Upvotes: 2
Reputation: 33476
I suggest using DataTable to create a column structure at runtime & adding rows. And then sort it using Column's name.
e.g. DataTable.Sort = "Column5 ASC, Column2 ASC" (pseudocode).
Upvotes: 0