34 lines
1.0 KiB
C#
34 lines
1.0 KiB
C#
using Harmonia.Core.Models;
|
|
using System.ComponentModel;
|
|
using System.Reflection;
|
|
|
|
namespace Harmonia.Core.Extensions;
|
|
|
|
public static class EnumerableExtensions
|
|
{
|
|
public static IOrderedEnumerable<T> SortBy<T>(this IEnumerable<T> source, SortOption[] sortOptions)
|
|
{
|
|
IOrderedEnumerable<T> orderedQuery = source.OrderBy(x => 0);
|
|
Type type = typeof(T);
|
|
|
|
foreach (SortOption sortOption in sortOptions)
|
|
{
|
|
PropertyInfo? property = type.GetProperty(sortOption.FieldName);
|
|
|
|
if (property == null)
|
|
continue;
|
|
|
|
switch (sortOption.Direction)
|
|
{
|
|
case ListSortDirection.Ascending:
|
|
orderedQuery = orderedQuery.ThenBy(x => property.GetValue(x));
|
|
break;
|
|
case ListSortDirection.Descending:
|
|
orderedQuery = orderedQuery.ThenByDescending(x => property.GetValue(x));
|
|
break;
|
|
}
|
|
}
|
|
|
|
return orderedQuery;
|
|
}
|
|
} |