Sorting Variables of Multidimensional Arrays

I have an array of integers: d []. for example (7 columns and multiple rows):

4 1 8 0 3 2 6

7 0 4 9 1 1 5

0 6 1 3 5 2 0

etc. At compile time, I don't know how many columns array d has. And I don't know at compile time which columns to use for orderby.

For example, you need to sort by: d [5], d [2], d [0], d [3]. But at runtime, I know the sort order of the columns. For example, the column indices are: 5, 2, 0, 3, which means columns d [5], d [2], d [0], d [3]. How can I order the array d using these column indices?

+1


a source to share


2 answers


Assuming you are using a jagged array ( int[][]

), you can use LINQ by concatenating 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 can also (alternatively) build a comparison to navigate to Array.Sort

.

+2


a source


I suggest using DataTable to create the column structure at runtime and add rows. And then sort it using the column name.



eg. DataTable.Sort = "Column5 ASC, Column2 ASC" (pseudocode).

0


a source







All Articles