问题描述
我正在创建使用Lambda/LINQ进行动态whereby和orderby的概念证明.以下代码适用于where表达式,但是我无法弄清楚如何通过表达式创建订单.对于这个例子,如果可能的话,我想保持简单;我宁愿不编写修改表达式树的代码.
I'm creating a proof of concept that uses Lambda/LINQ for dynamic where and orderby. The following code works for the where expression, but I can not figure out how to create an order by expression. For this example, if possible I would like to keep it simple; I would rather not write code that modifies an Expression Tree.
void Main()
{
DateTime productSince = DateTime.UtcNow.Subtract(new TimeSpan(1,30,0));
Expression<Func<Products, bool>> filter = d => d.CreatedDate > productSince && d.Price < 100 ;
List<Products> products = GetProducts(filter, Products);
Console.WriteLine(products);
}
private static List<Products> GetProducts(Expression<Func<Products, bool>> filter, Table<Products> Products)
{
var products = Products.Where(filter);
return products.ToList();
}
我想要的内容与以下内容相似,但无法找出通过表达式创建订单的代码.
What I want is similar to the following but can not figure out the code to create the order by expression.
void Main()
{
DateTime productSince = DateTime.UtcNow.Subtract(new TimeSpan(1,30,0));
Expression<Func<Products, bool>> filter = d => d.CreatedDate > productSince && d.Price < 100 ;
Expression<Func<Products, ????>> orderBy = d => ??????;
List<Products> products = GetProducts(filter, orderBy, Products);
Console.WriteLine(products);
}
private static List<Products> GetProducts(Expression<Func<Products, bool>> filter,
Expression<Func<Products, ???>> orderBy, Table<Products> Products)
{
var products = Products.Where(filter).OrderBy(orderBy);
return products.ToList();
}
如果您想知道,我正在使用LinqPad进行这种概念验证.
If you are wondering, I'm using LinqPad for this proof of concept.
推荐答案
private static List<Products> GetProducts<TOrderBy>(Expression<Func<Products, bool>> filter,
Expression<Func<Products, TOrderBy>> orderBy, Table<Products> Products)
{
var products = Products.Where(filter).OrderBy(orderBy);
return products.ToList();
}
如果您查看OrderBy扩展方法,它会接受Expression<Func<T, TOrderBy>>
,因为表达式可以导致任何类型的依赖项
If you look at OrderBy extension method it accepts a Expression<Func<T, TOrderBy>>
because the expression can result in any type depending
.OrderBy(x => x.ID) // <T, int>
.OrderBy(x => x.Name) // <T, string>
因此,您的包装器方法必须能够接受该泛型类型才能传入.
So therefor your wrapper method needs to be able to accept that generic type to pass in.
这篇关于为LINQ/Lambda创建OrderBy表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!