0

I have a C# datatable which currently sorts like this

using this code:

using this code

customTable.DefaultView.Sort = "Module DESC";

What I want to achieve is keep the intro entries at the top but the rest of the items should start with 1 and finish with 4, is there anything else I can apply to do that or I need to do custom coding?

The datatable is assembled in the code and its not coming up from any data source.

halfer
  • 19,824
  • 17
  • 99
  • 186
Laziale
  • 7,965
  • 46
  • 146
  • 262
  • create another column 'SortOrder' .......populate appropriately, sort on it – Mitch Wheat May 12 '17 at 07:29
  • You could also create a temp `DataTable`. Select the desired sort to temp then `CopyToDataTable()`. Some of the answers [in this link](http://stackoverflow.com/questions/9107916/sorting-rows-in-a-data-table) should be able to help. – P. Pat May 12 '17 at 07:34

1 Answers1

0

You can use LINQ:

customTable = customTable.AsEnumerable()
    .Select(row => new 
    { 
        row, 
        module = row.Field<string>("Module").TryGetInt()
    })
    .OrderBy(x => x.module.HasValue) // all numbers come last (true higher than false)
    .ThenBy(x => x.Module.GetValueOrDefault())  // order numbers ascending
    .Select(x => x.row)
    .CopyToDataTable();

Used this simple extension method to try-parse the int to an int?(if it's "Intro"it's null):

public static int? TryGetInt(this string item)
{
    int i;
    bool success = int.TryParse(item, out i);
    return success ? (int?)i : (int?)null;
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939