Sorting DataTable-columns
c#, datatable, sorting
Solution
You don't need to sort the columns in the DataTable object, just copy the column names to an array and sort the array. Then use the array to access the column values in the right order.
Sample:
class Program
{
static void Main(string[] args)
{
var dt = new DataTable { Columns = { "A3", "A2", "B1", "B3", "B2", "A1" } };
dt.BeginLoadData();
dt.Rows.Add("A3val", "A2val", "B1val", "B3val", "B2val", "A1val");
dt.EndLoadData();
string[] names=new string[dt.Columns.Count];
for (int i = 0; i < dt.Columns.Count;i++ )
{
names[i] = dt.Columns[i].ColumnName;
}
Array.Sort(names);
foreach (var name in names)
{
Console.Out.WriteLine("{0}={1}", name, dt.Rows[0][name]);
}
Console.ReadLine();
}
Problem
I have a datatable something like this: ``` | Col1 | Col6 | Col3 | Col43 | Col0 | --------------------------------------------------- RowA | 1 | 6 | 54 | 4 | 123 | ``` As you see, the `Col`s are not sorted by their numbers. That is what I want it to look like after the "magic": ``` | Col0 | Col1 | Col3 | Col6 | Col43 | --------------------------------------------------- RowA | 123 | 1 | 54 | 6 | 4 | ``` Is there a built-in function for such things in C#? And if not, how could I get started with this?