using System;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;

/// <summary>
/// This static class provides statics methods to naturally sort a datatable column. 
/// </summary>
public static class NaturalSortService
    /// <summary>
    /// </summary>
    /// <param name="table">DataTable with DataRows to be sorted</param>
    /// <param name="ColumnToSort">The name of the column to sort</param>
    /// <returns>Returns an EnumerableRowCollection of a DataRow type. The Collection is sorted naturally in a single column.</returns>
    public static System.Data.EnumerableRowCollection<System.Data.DataRow> Sort(DataTable table, string ColumnToSort)
        //Used to determine numerical values which are placed first in importance.
        Func<string, object> convert = str =>
            int returnInt = 0;
            if (int.TryParse(str, out returnInt))
                return returnInt;
                return str;

        //Using the EnumerableComparer from TestSampleResults.Domain.Services.EnumerableComparer
        var sorted = (from t in table.AsEnumerable()
                        select t).OrderBy(
                    str => Regex.Split(str.Field<string>(ColumnToSort).Replace(" ", ""), "([0-9]+)").Select(convert),
                    new EnumerableComparer<object>());

        return sorted;
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter