Linq集团由id

时间:2014-04-24 09:59:45

标签: c# linq linq-group

var query = from c in context.Auto
            join r in context.Label on c.idAutoChar equals r.idAutoChar
            join g in context.Rent on c.idAuto equals g.idAuto
            where c.idAutoChar == r.idAutoChar && c.idAuto == g.idAuto
            group new {c, r, g} by new {c.idAuto, r.Name, c.RegNumber, g.Summ} into v
            select new
            {
                v.Key.idAuto,
                v.Key.Name,
                v.Key.RegNumber,
                Sum = (from b in v select v.Key.Summ).Sum()
            };

我需要通过idAuto将一个SUM(Summ)列分组,但它无法正常工作。能否请你帮忙。

2 个答案:

答案 0 :(得分:1)

var query = from c in context.Auto
                 join r in context.Label on c.idAutoChar equals r.idAutoChar
                 join g in context.Rent on c.idAuto equals g.idAuto
                 //where c.idAutoChar == r.idAutoChar && c.idAuto == g.idAuto //???
                 group new {c, r, g} by new {c.idAuto, r.Name, c.RegNumber} into v
                         select new
                         {
                             v.Key.idAuto,
                             v.Key.Name,
                             v.Key.RegNumber,
                             Sum = v.Sum(item => item.Key.Summ)
                         };

使用Sum = v.Sum(item => item.Key.Summ)并且不要按Summ分组,否则会为每个不同的Summ值生成一个组项。

顺便说一句,为什么你需要where条件 - 它会复制你的联接的on条件

答案 1 :(得分:0)

假设g.Summ是一个你想要求和的数值,而不是你真正想要分组的东西,那么它就不应该是密钥的一部分。

我无法对此进行测试,但这样的事情可能就是答案:

c in context.Auto
                     join r in context.Label on c.idAutoChar equals r.idAutoChar
                     join g in context.Rent on c.idAuto equals g.idAuto
                     where c.idAutoChar == r.idAutoChar && c.idAuto == g.idAuto
                     group new {c, r, g} by new {c.idAuto, r.Name, c.RegNumber} into v
                     select new
                     {
                         v.Key.idAuto,
                         v.Key.Name,
                         v.Key.RegNumber,
                         Sum = (from b in v
                                           select b.Summ).Sum()
                     };

注意我们不在组中包含c.Summ,而Sum则超过b.Summ。我还认为在这个linq语句中实际上并不需要g(Rent?)。