为LINQ / Lambda创建一个OrderBy表达式

时间:2011-04-23 18:58:16

标签: c# linq lambda

我正在创建一个概念证明,它将Lambda / LINQ用于动态where和orderby。以下代码适用于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进行此概念验证。

2 个答案:

答案 0 :(得分:19)

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>

因此,您的包装器方法需要能够接受传入的泛型类型。

答案 1 :(得分:12)

您正在寻找的是:

Expression<Func<Products, dynamic>>;

尝试创建一个结构/类来保存Expression,如果它是升序或降序。