Tuesday, August 14, 2012

Simple Way to Sort a DataTable in .NET

I encountered a situation where I had to populate a DataTable with different types of Equipment.  Depending on different factors, the combination of Equipment types varies.  Here are the primary 3 fields in the table:
  1. Unit Num
  2. Description
  3. Equip Type
After the table was fully populated, it became evident that the Unit Num values were not sorted in an orderly sequence.  So I investigated how to sort it in this manner.  I quickly discovered that there was no method to do this in one step but after a short investigation and a little trial & error I discovered a relatively simple approach:

dataTable.Columns.Add("iUnit_No", typeof(Int32), "Convert(Unit_No, 'System.Int32')");  // Add a numeric column that's equivalent to "Unit_No"
dataTable.DefaultView.Sort = "iUnit_No ASC";  // Sort the DefaultView according to this new numeric column
dataTable = dataTable.DefaultView.ToTable(false, "Description", "Unit_No", "Equip_Type");  // Copy the contents of the DefaultView back to the original table, specifying only the columns we want in it
A few lines of code but it works well!

1 comment:

  1. Sorting is almost same as filtering. For sorting one needs to give the the first parameter null and the second parameter as ones want to sort.

    DataRow[] rows1 = objTable.Select(“”,”salesDate DESC, salesID ASC ”);

    It will return sorted row1 array of DataRow.

    DataTable can be sorted by another way. Such as

    DataView objDataView=objTable.DefaultView;

    objDataView.Sort=”salesDate DESC, salesID ASC”;

    objTable=objDataView.ToTable();
    more help read dapfor. com

    ReplyDelete