-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIQueryableExtensions.cs
More file actions
35 lines (28 loc) · 1.08 KB
/
Copy pathIQueryableExtensions.cs
File metadata and controls
35 lines (28 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace EzySorting
{
public static class IQueryableExtensions
{
public static IQueryable<T> AddSort<T>(this IQueryable<T> queryable, SortModel sortModel)
where T : class
{
if (sortModel == null || string.IsNullOrEmpty(sortModel?.Property)) return queryable;
var lambda = GenerateOrderByLambda<T>(sortModel.Property);
queryable = sortModel.SortDirection == SortDirection.Ascending
? queryable.OrderBy(lambda)
: queryable.OrderByDescending(lambda);
return queryable;
}
private static Expression<Func<T, object>> GenerateOrderByLambda<T>(string property)
{
var param = Expression.Parameter(typeof(T));
var prop = Expression.Property(param, property);
var expAsObject = Expression.Convert(prop, typeof(object));
return Expression.Lambda<Func<T, object>>(expAsObject, param);
}
}
}