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!