2

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.

Community
  • 1
  • 1
Koffi
  • 23
  • 4
  • 1
    Replace your `OrderBy` with `OrderByAlphaNumeric`. – Rob Jan 06 '17 at 11:31
  • Do you mean `DataTable dtNew = dv.Table.AsEnumerable().OrderByAlphaNumeric(x => x.Field("code_name")).CopyToDataTable();`? It doesn't work (error "does not contain a definition for and no extension method accepting a first argument of type could be found (are you missing a using directive or an assembly reference?)"). – Koffi Jan 06 '17 at 12:41
  • Yes, that's what you'd write. Not sure why you're getting an error - its likely you haven't referenced your extension class. What is the type it's looking for? (but it in backticks - ` - otherwise it's stripped from the comment) – Rob Jan 06 '17 at 12:46
  • I've changed as suggested. But implementation is also one of my issues, I don't know how to implement this "public static IEnumerable OrderByAlphaNumeric [...]". Should I create in folder "AppCode" a class named OrderByAlphaNumeric.cs? What should be the namespace in this class, then? – Koffi Jan 06 '17 at 13:13

1 Answers1

1

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.

Stuart
  • 5,358
  • 19
  • 28