linq加入groupby后选择

时间:2013-01-28 22:27:51

标签: linq join group-by

我需要在常规的sql查询命令中构造这样的linq:

select t1.vendorcode, t1.location, sum(t1.sales)
from table1 t1
where t1(vendorCode, location) in
      (select t2.vendorCode, t2.location from table2 t2) 
groupby t1.vendorCode, t1.location

我构建linq如下:

query = from t1 in table1
where ...
join t2 in table2 on new
{
  t2.vendorcode, t2.location
} equals new
{ 
  t1.vendorcode, t1.location 
}

我的问题是:我应该如何构建这个linq?我是否需要另一个子查询,还是可以添加更多group by和select语句来完成此linq?

2 个答案:

答案 0 :(得分:1)

您不需要添加另一个group by子句 - 您只需选择总和:

var query = from t1 in table1
            join t2 in table2 
              on new { t1.vendorcode, t1.location } equals
                 new { t2.vendorcode, t2.location }
            group t1 by new { t1.vendorcode, t1.location } into g
            select new { 
                g.Key.vendorcode,
                g.Key.location, 
                g.Sum(t1 => t1.sale)
            };

如果只有table2中有一条记录与任何特定的供应商代码/位置对,那么它将起作用。但是,如果可以有多个记录,那么它就不起作用了 - 你可能想要更像的东西:

var query = from t1 in table1
            where table2.Select(t2 => new { t2.vendorcode, t2.location })
                        .Contains(new { t1.vendorcode, t1.location })
            group t1 by new { t1.vendorcode, t1.location } into g
            select new { 
                g.Key.vendorcode,
                g.Key.location, 
                g.Sum(t1 => t1.sale)
            };

这在逻辑上是你的“存在”版本。

答案 1 :(得分:0)

这应该这样做

var query =
    from t1 in table1

    join t2 in table2
    on new { vc = t1.vendorcode, lc = t1.location }
    equals new { vc = t2.vendorcode, lc = t2.location }

    group t1 by new { vc = t1.vendorcode, lc = t1.location };