namespace Groceries.Components; using System.Linq.Expressions; public static class DataSort { public static DataSort By(Expression> expression, string key) => new((source, desc) => desc ? source.OrderByDescending(expression) : source.OrderBy(expression), key); public static DataSort ByDescending(Expression> expression, string key) => new((source, desc) => desc ? source.OrderBy(expression) : source.OrderByDescending(expression), key); } public class DataSort { private readonly Func, bool, IOrderedQueryable> first; private readonly List, bool, IOrderedQueryable>> thens = []; internal DataSort(Func, bool, IOrderedQueryable> first, string key) { this.first = first; Key = key; } public string Key { get; } public DataSort ThenBy(Expression> expression) { thens.Add((source, desc) => desc ? source.ThenByDescending(expression) : source.ThenBy(expression)); return this; } public DataSort ThenByDescending(Expression> expression) { thens.Add((source, desc) => desc ? source.ThenBy(expression) : source.ThenByDescending(expression)); return this; } internal IOrderedQueryable Apply(IQueryable source, bool descending) { var ordered = first(source, descending); foreach (var then in thens) { ordered = then(ordered, descending); } return ordered; } }