我正在创建一个使用Lambda/LINQ进行动态位置和顺序的概念证明。下面的代码适用于where表达式,但我不知道如何创建按表达式排序。对于这个例子,如果可能的话,我想保持简单;我宁愿不编写修改表达式树的代码。
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();
}
我想要的是类似于下面的代码,但不知道如何创建按表达式排序的代码
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来验证这个概念。
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>>
因为表达式可以产生任何类型取决于
.OrderBy(x => x.ID) // <T, int>
.OrderBy(x => x.Name) // <T, string>
因此,您的包装器方法需要能够接受传入的泛型类型
你要找的是:
Expression<Func<Products, dynamic>>;
尝试创建一个结构/类来保存表达式,如果它是升序或降序。