using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace API.Extensions
{
public static class EnumerableExtensions
{
private static readonly Regex Regex = new Regex(@"\d+", RegexOptions.Compiled, TimeSpan.FromMilliseconds(500));
///
/// A natural sort implementation
///
/// IEnumerable to process
/// Function that produces a string. Does not support null values
/// Defaults to CurrentCulture
///
/// Sorted Enumerable
public static IEnumerable OrderByNatural(this IEnumerable items, Func selector, StringComparer stringComparer = null)
{
var maxDigits = items
.SelectMany(i => Regex.Matches(selector(i))
.Select(digitChunk => (int?)digitChunk.Value.Length))
.Max() ?? 0;
return items.OrderBy(i => Regex.Replace(selector(i), match => match.Value.PadLeft(maxDigits, '0')), stringComparer ?? StringComparer.CurrentCulture);
}
}
}