我怎样才能重新使用LINQ语句中的表达式? [英] How can I reuse expressions within LINQ statements?

查看:118
本文介绍了我怎样才能重新使用LINQ语句中的表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢重用DRY原因表情,但我怎么重新使用LINQ语句中的表达式?



例如



 公共静态类MyExpressions {
公共静态表达式来; Func键<产品,布尔> > IsAGoodProduct(){
回报率(P)=>图像质量→3;
}
}

和想用在LINQ语句,所以

  VAR goodProds =从dataContext.Products 
,其中p ????? //我怎么在这里使用IsAGoodProduct?
的选择P;



当然,我可以使用IQueryableExtension.Where功能,但是这将使连接等功能很多丑陋对于更复杂的查询。



这是可能的,或者是LINQ的?


解决方案<限制/ DIV>

如果您从LINQ语法糖移动它是可能的:

  VAR goodProds = dataContext.Products.Where (MyExpressions.IsAGoodProduct()); 



如果没有它,这是不可能的。



有什么能阻止你混合两种样式虽然建立一个单一的查询



例如:



<$在dataContext.Products
。凡(MyExpressions.IsAGoodProduct())
群p p $ p> VAR goodProds =从对由p.Category为G
选择新{类​​别= g.Key,ProductCount = g.Group.Count()};


I like to reuse expressions for DRY reasons, but how do I reuse the expressions within a LINQ statement?

e.g.

I have

public static class MyExpressions {
    public static Expression<Func<Product,bool>> IsAGoodProduct() {
        return (p) => p.Quality>3;
    }
}

And would like to use that in LINQ statements, so

  var goodProds = from p in dataContext.Products
                  where ????? // how do I use IsAGoodProduct here?
                  select p;

Sure, I could use the IQueryableExtension.Where function, but that would make joins and other functions alot uglier for more complex queries.

Is this possible or is it a limitation of LINQ?

解决方案

If you move from the LINQ syntactic sugar it is possible:

var goodProds = dataContext.Products.Where(MyExpressions.IsAGoodProduct());

Without it, it isn't possible.

There's nothing to stop you mixing the two styles to build a single query though.

Example:

  var goodProds = from p in dataContext.Products
                                       .Where(MyExpressions.IsAGoodProduct())
                  group p by p.Category into g 
                  select new {Category = g.Key, ProductCount = g.Group.Count()};

这篇关于我怎样才能重新使用LINQ语句中的表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆