Files
Auth/Auth.Core/Utility/QueryableExtensions.cs
2026-08-05 21:15:14 +03:00

31 lines
1.1 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace Auth.Core.Utility;
public static class QueryableExtensions
{
public static IQueryable<T> ApplySorting<T>(this IQueryable<T> source, SortModel sortBy)
{
// Parameter for lambda expression, e.g., "p" in "p => p.Property"
var parameter = Expression.Parameter(typeof(T), "p");
// Access the property on the parameter, e.g., "p.Property"
var property = Expression.Property(parameter, sortBy.SortBy);
// Cast property access to an object (boxing value types)
var converted = Expression.Convert(property, typeof(object));
// Create the lambda expression, e.g., "p => (object)p.Property"
var keySelector = Expression.Lambda<Func<T, object>>(converted, parameter);
// Apply OrderBy or OrderByDescending based on the ascending flag
return sortBy.SortDirection == SortDir.Ascending
? source.OrderBy(keySelector)
: source.OrderByDescending(keySelector);
}
}