简体   繁体   中英

C# multi-dimension array sort based on user input

How can I sort a 2D array in C#

I have looked at other answers to this question but they don't do exactly what I need.

The array is variable height * 5 across

The array holds strings

I need the array sorted based on either column, for example sort in alphabetical the third column, however all other columns must be updated.

Does anyone know of a quick and easy solution?

My code is a mess, here is a shortened version:

string[,] tmp = new string[2, 3];//this is filled with strings
string y = Console.ReadLine();
int x = Convert.ToInt32(y);

// sort tmp based on x column

How do I sort a two-dimensional array in C#? contains a possible solution to this by reading your data into a datatable and then using the object's methods to sort:

// 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");

So first we'll want to convert the multi-dimensional array into a sequence of single-dimensional arrays representing the rows, so that each row can be manipulated as a unit:

public static IEnumerable<T[]> GetRows<T>(T[,] array)
{
    for (int i = 0; i < array.GetLength(0); i++)
    {
        T[] row = new T[array.GetLength(1)];
        for (int j = 0; j < row.Length; j++)
        {
            row[j] = array[i, j];
        }
        yield return row;
    }
}

Then we'll also need a method that does the reverse to get a multi-dimensional array back when we're done:

public static T[,] ToMultiDimensionalArray<T>(T[][] rows)
{
    T[,] output = new T[rows.Length, rows[0].Length];

    for (int i = 0; i < rows.Length; i++)
        for (int j = 0; j < rows[0].Length; j++)
        {
            output[i, j] = rows[i][j];
        }
    return output;
}

Now we just need to sort a sequence of arrays, and Linq makes this quite easy:

tmp = ToMultiDimensionalArray(GetRows(tmp)
    .OrderBy(row => row[2]).ToArray());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM