Laziale Laziale - 6 months ago 24
C# Question

c# datatable custom sort in the code

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.

Thanks in advance, Laziale

Answer Source

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;
}