Reputation: 23
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.
Upvotes: 2
Views: 1518
Reputation: 5496
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.
Upvotes: 1