C#通用Linq查询
我需要编写一些通用搜索方法,如下所示:C#通用Linq查询,c#,linq,C#,Linq,我需要编写一些通用搜索方法,如下所示: public List<T> Search<T>(SearchParamsBase searchParams) { using (var context = new TestEntities()) { var dataType = TypeMap.Get(typeof (T)); var dataSet = context.Set(dataType); var sea
public List<T> Search<T>(SearchParamsBase searchParams)
{
using (var context = new TestEntities())
{
var dataType = TypeMap.Get(typeof (T));
var dataSet = context.Set(dataType);
var searchQuery = CreateQuery((IEnumerable<object>) dataSet), searchParams)
return searchQuery.ToList()
}
}
我怎样才能正确地实施这个想法 这里基本上要做的是动态构造一个LINQ查询。为此,需要在运行时修改/构建表达式树。如果您不熟悉表达式树和
表达式
类型,我建议您阅读本文以及“另请参阅”部分中的参考页面:
现在您已经了解了基本概念,让我们实现动态排序。下面的方法是对IQueryable
的扩展,这意味着它不仅适用于列表,而且适用于每个LINQ数据源,因此您还可以直接对数据库使用它(这在分页和排序方面比内存操作更有效)。该方法采用您要按其排序的属性名称和排序方向(升序/降序):
为动态筛选创建扩展方法遵循相同的模式。如果您理解上面的代码,这对您来说不会是一个问题
CreateQuery(IEnumerable<object> collection, SearchParamsBase searchParams)
{
var search = (SomeSearchImplementation)searchParams;
// filter
collection = collection.Where(x => x.Name == search.Name);
// select page
collection = collection.Skip(search.Page * search.CountPerPage);
collection = collection.Take(search.CountPerPage);
// order by and so on
// ...
return collection;
}
public static IQueryable<T> OrderByDynamic<T>(this IQueryable<T> query, string sortColumn, bool descending)
{
// Dynamically creates a call like this: query.OrderBy(p => p.SortColumn)
var parameter = Expression.Parameter(typeof(T), "p");
string command = "OrderBy";
if (descending)
{
command = "OrderByDescending";
}
Expression resultExpression = null;
var property = typeof(T).GetProperty(sortColumn);
// this is the part p.SortColumn
var propertyAccess = Expression.MakeMemberAccess(parameter, property);
// this is the part p => p.SortColumn
var orderByExpression = Expression.Lambda(propertyAccess, parameter);
// finally, call the "OrderBy" / "OrderByDescending" method with the order by lamba expression
resultExpression = Expression.Call(typeof(Queryable), command, new Type[] { typeof(T), property.PropertyType },
query.Expression, Expression.Quote(orderByExpression));
return query.Provider.CreateQuery<T>(resultExpression);
}
dataSet.OrderByDynamic("Name", false)