使用SUM& Linq的GROUP BY集合

时间:2015-01-16 11:03:12

标签: c# linq

我想使用SUM& linq GOUP BY。我在collection&想要使用下面的query执行collection linq

public class Summary
    {
        public int Month { get; set; }
        public int Year { get; set; }        
        public double Wages { get; set; }
        public double AccNo22 { get; set; }
        public double AccNo21 { get; set; }

    }

List<Summary> list = new List<Summary>();

for (int i = 0; i < data.Rows.Count; i++)
{

     Summary model = new Summary();

     model.Month = int.Parse(data.Rows[i]["MonthNumber"].ToString());
     model.Year = int.Parse(data.Rows[i]["Year"].ToString());         
     model.AccNo22 = 0;
     model.AccNo21 = 0;

     list.Add(model);   
}

查询: -

SELECT Year, Month, SUM(ACCNO21) AS ACC21,SUM(ACCNO22) AS ACC22 FROM AboveList
WHERE  (((Month >=  3  AND Month <= 12) AND Year = '2015') OR ((Month >= 1  AND Month <= 2) AND Year = '2016')) 
    GROUP BY Month,Year")

我正在尝试: -

var newCollection = list
    .GroupBy(a => a.Month, b => b.Year)
    .Select(a => new { Wages = a.Sum(a.Wages)})    
    .ToList();

2 个答案:

答案 0 :(得分:1)

你需要像这样投影: -

 .Select(a => new { Wages = a.Sum(b => b.Wages)})

依此类推AccNo22,AccNo21等。

以下是完整的查询: -

var result= list.Where(x => (x.Month >= 3 && x.Month <=12 && x.Year == 2015) ||
                              (x.Month >=1 && x.Month <=2 && x.Year == 2016)
                      )
                    .GroupBy(x => new {x.Month, x.Year})
                    .Select(x => new {
                         Year = x.Key.Year,
                         Month = x.Key.Month,
                         AccNo21 = x.Sum(z => z.AccNo21),
                         AccNo22 = x.Sum(z => z.AccNo22)
                    });

答案 1 :(得分:1)

好吧,您可以先在列表中进行过滤,然后分组并选择元素。

var newCollection = list
                    .Where(m => (m.Month >= 3 && m.Month <=12 && m.Year == 2015) ||
                                (m.Month >=1 && m.Month <=2 && m.Year == 2016)
                          )
                    .GroupBy(m => new{m.Month, m.Year})
                    .Select(m => new {
                         year = m.Key.Year,
                         month = m.Key.Month,
                         AccNo21 = m.Sum(g => g.AccNo21),
                         AccNo22 = m.Sum(g => g.AccNo22)
                    });