High-Performance Development - C#, VB, SQL, ASP.NET

Slogan Text

This article describes how to sort a DataTable.

Assume we have a DataTable containing several times (the date portion is irrelevant) constructed as follows:

       DataRow Dr;
    DataTable Times;
    Times = new DataTable();
    Times.Columns.Add("Time", typeof(DateTime));
    Dr = Times.NewRow();
    Dr["Time"] = new DateTime(1900,1,1, 8, 0, 0);
    Times.Rows.Add(Dr);
    Dr = Times.NewRow();
    Dr["Time"] = new DateTime(1900,1,1, 6, 0, 0);
    Times.Rows.Add(Dr);
    Dr = Times.NewRow();
    Dr["Time"] = new DateTime(1900,1,1, 5, 0, 0);
    Times.Rows.Add(Dr);

We want to sort the rows by the Time column.

  1. Copy the source rows to a new DataTable.
  2. Set DefaultView.Sort to the name of the column to be used for sorting.
  3. Select the rows from the sorted DataTable.
  4. Copy the rows back into the source DataTable using the ImportRow method.
    DataRow[] Drs;
    DataTable DtSorted;
    DtSorted = Times.Copy();
    DtSorted.DefaultView.Sort = "Time";
    Drs = DtSorted.Select();
    Times.Rows.Clear();
    foreach (DataRow Dr3 in Drs)
    {
        Times.ImportRow(Dr3);
    }

This example shows the basic operations sorting a DataTable. Your application may have performance or other requirements which may require customization of the code for your needs.