How to Sort a DataTable
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.
- Copy the source rows to a new DataTable.
- Set DefaultView.Sort to the name of the column to be used for sorting.
- Select the rows from the sorted DataTable.
- 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.
|