LINQ加入过滤条件

时间:2010-01-19 23:36:53

标签: .net linq linq-to-sql join criteria

如何在linq中完成这样的事情?它在JOIN上有过滤条件。

这取自这个问题:SQL Filter criteria in join criteria or where clause which is more efficient

select salesman.salesmanid, max(sales.quantity)
from salesman
inner join sales  on salesman.salesmanid =sales.salesmanid 
              and sales.salesdate < salesman.promotiondate
group by salesman.salesmanid

由于

2 个答案:

答案 0 :(得分:3)

除了join之外,你不能equals,但这可能不是你想要的。我认为SQL查询写得很笨,日期比较应该在WHERE子句中,但我认为这是主观的。无论如何,这是在Linq中唯一的方式:

var results =
    from sm in salesman
    join s in sales on sm.salesmanid equals s.salesmanid
    where s.salesdate < sm.promotiondate
    group s by s.salesmanid into g
    select new { salesmanid = g.Key, maxsales = g.Max(s => s.quantity) };

注意 - 更正了组线上的拼写错误

答案 1 :(得分:0)

假设您的表之间有导航属性,您可以将连接保留为实体框架。

var results = from s in salesmen
              group s by s.salesmanid
              select new
              {
                  s.salesmanid,
                  maxsales = s.sales
                      .where(x => s.salesdate < x.promotiondate)
                      .max(x => x.quantity)
              };