LINQ join with filter criteria

自闭症网瘾萝莉.ら 提交于 2019-12-11 02:18:13

问题


How is something like this done in linq? It has filter criteria on the JOIN.

This is taken from this question: 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

Thanks


回答1:


You can't join on anything other than equals, but that's probably not what you want here anyway. I would contend that the SQL query is awkwardly written and that the date comparison should be in a WHERE clause, but I suppose that's subjective. Anyway, that's the only way to do it in 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) };

Note - corrected typo on group line




回答2:


Assuming you have navigation properties between your tables, you can leave the join to entity framework.

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)
              };


来源:https://stackoverflow.com/questions/2098041/linq-join-with-filter-criteria

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!