web-app-template/backend/app/app.Data/LinqExtension.cs

30 lines
1.1 KiB
C#
Raw Normal View History

2022-02-20 13:43:25 +01:00
using System;
using System.Linq;
using System.Linq.Expressions;
namespace app.Data
{
public static class LinqExtension
{
public static IQueryable<T> OrderByMember<T>(this IQueryable<T> q, string SortField)
{
var param = Expression.Parameter(typeof(T), "p");
var prop = Expression.Property(param, SortField);
var exp = Expression.Lambda(prop, param);
Type[] types = new Type[] { q.ElementType, exp.Body.Type };
var mce = Expression.Call(typeof(Queryable), "OrderBy", types, q.Expression, exp);
return q.Provider.CreateQuery<T>(mce);
}
public static IQueryable<T> OrderByMemberDescending<T>(this IQueryable<T> q, string SortField)
{
var param = Expression.Parameter(typeof(T), "p");
var prop = Expression.Property(param, SortField);
var exp = Expression.Lambda(prop, param);
Type[] types = new Type[] { q.ElementType, exp.Body.Type };
var mce = Expression.Call(typeof(Queryable), "OrderByDescending", types, q.Expression, exp);
return q.Provider.CreateQuery<T>(mce);
}
}
}