Natural sort order in C# - implementation


I'd like to implement a natural sorting using this:

public static IEnumerable<T> OrderByAlphaNumeric<T>(this IEnumerable<T> source, Func<T, string> selector)
    int max = source
        .SelectMany(i => Regex.Matches(selector(i), @"\d+").Cast<Match>().Select(m => (int?)m.Value.Length))
        .Max() ?? 0;

    return source.OrderBy(i => Regex.Replace(selector(i), @"\d+", m => m.Value.PadLeft(max, '0')));

(taken from Natural Sort Order in C#)

I have a dataview dv which contains (among others) a column code_name. I'd like to copy the data of this dataview into a new datatable dtNew with a natural sort on the column code_name. I guess the code should be something like:

DataTable dtNew = dv.Table.AsEnumerable().OrderBy(x => x.Field<string>("code_name"),OrderByAlphaNumeric<T>).CopyToDataTable();

But I don't understand anything in how to manipulate IEnumerable<T> OrderByAlphaNumeric<T> in my context.

Show source
| sorting   | c#   |   2017-01-06 12:01 1 Answers

Answers to Natural sort order in C# - implementation ( 1 )

  1. 2017-01-06 13:01

    I believe you want to use it like this:

    DataTable dtNew = dv.Table.AsEnumerable().OrderByAlphaNumeric(x => x.Field<string>("code_name")).CopyToDataTable();

    Be sure to open the namespace containing OrderByAlphaNumeric where you use this code.

Leave a reply to - Natural sort order in C# - implementation

◀ Go back