C# · 12月 31, 2021

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

我正在创建一个概念证明,它使用Lambda / LINQ来进行动态的和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,bool>> filter = d => d.CreatedDate > productSince && d.Price < 100 ; Expression<Func<Products,????>> orderBy = d => ??????; List<Products> products = GetProducts(filter,orderBy,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,TOrderBy>> orderBy,Table<Products> Products){ var products = Products.Where(filter).OrderBy(orderBy); return products.ToList();}

如果你看到OrderBy扩展方法,它接受一个表达式< Func< T,TOrderBy>>因为表达式可能导致任何类型的依赖

.OrderBy(x => x.ID) // <T,int>.OrderBy(x => x.Name) // <T,string>

因此,您的包装方法需要能够接受通用类型.