按列LINQ使用组

时间:2013-02-19 05:58:46

标签: linq

我有下表

Date              GRP                Open

1/1/2011         A                    2
1/1/2011         B                    3
2/2/2011         C                    5

Group列是一些名为“Groups”A + B = Y的一部分 和C构成Z“

我需要按日期分组的Open和GRP的总和分别为

Date              Y     Z     

 1/1/2011         5     0
 2/2/2011         0     5

以下是我试过的代码

List<string> Y = new List<string>() { "A", "B" };
List<string> C = new List<string>() { "Z" };
from item in temp group item by new { RD = item.Field<DateTime>("date"),
Group= 
(Y.Contains(item.Field<string>("GRP")) ? "Y" :
 C.Contains(item.Field<string>"GRP")) ? "Z" :                                                 
                              }
                                             into grptbl
                                             select new
                                             {
                                                 RD = grptbl.Key.RD,
                                               A=grptbl.Where(x=>x.Field<string>("Group")=="Y").Sum(x=>x.Field<Int64>("Open")) 
,
                 Z= grptbl.Where(x=>x.Field<string>("Group")=="Z").Sum     (x=>x.Field<Int64>("Open")) };

看起来很好,但是抱怨说在grptable中,“select”子句中不存在“Group”列

1 个答案:

答案 0 :(得分:0)

回答了它

List<string> Y = new List<string>() { "A", "B" };
List<string> C = new List<string>() { "Z" };
from l in (from item in temp group item by new { 
 RD = item.Field<DateTime>("date"),
 Y=Y.Contains(item.Field<string>("GRP")) ? "Y" :item.Field<Int64>("open") : 0,
 Z=C.Contains(item.Field<string>"GRP")) ? "Z":item.Field<Int64>("open") :0                                                 
                          }
                                         into grptbl
                                         select new
                                         {
                                             RD = grptbl.Key.RD,
                                           Y=grptbl.Key.Y,
                                           Z=grptbl.Key.Z
                                          } )
    group l by new {l.RD} into g
    {
     RD=g.Key.RD,
     Y=g.Sum(x=>x.Y),
     Z=g.Sum(x=>x.Z)};