Anup
Anup

Reputation: 9738

Using SUM & GROUP BY on Collection in Linq

I want to use SUM & GOUP BY in linq. I have records in a collection & want to use the below query to execute on the collection by 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);   
}

Query :-

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")

I am trying :-

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

Upvotes: 0

Views: 57

Answers (2)

Rahul Singh
Rahul Singh

Reputation: 21795

You need to project it like this:-

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

and so on for AccNo22, AccNo21 etc.

Here is the complete query:-

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)
                    });

Upvotes: 1

Rapha&#235;l Althaus
Rapha&#235;l Althaus

Reputation: 60503

Well, you can filter on list first, then group by and select elements.

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)
                    });

Upvotes: 1

Related Questions