Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting DataTable-columns

I have a datatable something like this:

     |  Col1  |  Col6  |  Col3  |  Col43 |  Col0  |
---------------------------------------------------
RowA |   1    |    6   |   54   |    4   |   123  |

As you see, the Cols 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?

like image 242
F.P Avatar asked Jun 24 '26 23:06

F.P


2 Answers

You can do the column sorting in the table itself:

dt.Columns["Col0"].SetOrdinal(0);
dt.Columns["Col1"].SetOrdinal(1);
dt.Columns["Col2"].SetOrdinal(2);
like image 64
JBrooks Avatar answered Jun 27 '26 11:06

JBrooks


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();
        }
like image 23
Ariel Popovsky Avatar answered Jun 27 '26 12:06

Ariel Popovsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!