c.NaturalSort

PHOTO EMBED

Wed Sep 22 2021 14:34:19 GMT+0000 (Coordinated Universal Time)

Saved by @rick_m #c#

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

var naturallySortedProperties = NaturalSortService.Sort(dataTable, "Key").Select(s => new Property { Key = s.Field<string>("Key"), Value = s.Field<Guid>("Value").ToString() }).ToList();