集团&使用LINQ聚合多个列

时间:2013-11-19 01:14:15

标签: linq

我正试图使用​​LINQ和C#从csv文件中执行分组和计算行。

(样本csv)

T5,,929,,O,PPT-DAY,4,,,18.09,,ACXD:DSC,,,,,,,,,,,
T5,,929,,O,PPT-DAY,4,,,18.09,,ACXD:DSC,,,,,,,,,,,
T5,,644,,O,PPT-ANNUAL LEAVE,1,,,850.23,,INTERNAL,,,,,,,,,,,
T5,,900,,O,PPT-ANNUAL LEAVE,1,,,42.51,,INTERNAL,,,,,,,,,,,
T5,DEFAULT,674,,O,PPT-DAY,2,,,18.09,,ACXD:DSC,,,,,,,,,,,
T5,,674,,O,PPT-PERSONAL LEAVE-ON,8,,,19.9,,INTERNAL,,,,,,,,,,,

SQL等效

SELECT Col3  
      ,Col5
      ,Col6
      ,SUM(Col7) as [hours]     
      ,AVG(Col10) as [pay]    
      ,Col12     
  FROM mytable
  GROUP BY Col3, Col5, Col6, Col12
  ORDER BY Col3, Col5, Col6, Col12

我使用其他线程进行了一些尝试,但我正在努力进行多列分组和计算。任何建议都会非常感激。

1 个答案:

答案 0 :(得分:5)

试试这个,

var query = (from t in mytable
             orderby t.Col3, t.Col5, t.Col6, t.Col12
             group t by new {t.Col3, t.Col5, t.Col6, t.Col12} into grp
             select new
                {
                    grp.Key.Col3,
                    grp.Key.Col5,
                    grp.Key.Col6,
                    hours = grp.Sum(t => t.Col7),
                    pay = grp.Average(t => t.Col10),
                    grp.Key.Col12,
                }).ToList();

OR

   var query = mytable.GroupBy(t => new {t.Col3, t.Col5, t.Col6, t.Col12})
               .Select(grp => new
               {
                   grp.Key.Col3,
                   grp.Key.Col5,
                   grp.Key.Col6,
                   hours = grp.Sum(t => t.Col7),
                   pay = grp.Average(t => t.Col10),
                   grp.Key.Col12,
               })
               .OrderBy(t => new { t.Col3, t.Col5, t.Col6, t.Col12 }).ToList();