Troskyvs
Troskyvs

Reputation: 8047

How to write "group by" + "sum" in just one clause?

I've got sample data of

IEnumerable<Employee> ie;

Where Employee contains "Name, Salary, Department_id"

I can use 2 clauses to group by Department id and them "Sum" every group in a for loop, like below:

        var group3 = ie.GroupBy(x => x.Department_id);
        foreach (var g in group3)
        {
            Console.WriteLine(g.Sum(x=>x.Salary));
        }

Yes it works, but can I get my code simpler, I mean how can I get rid of the foreach loop to calculate my Sum() just in my linq statement and write it like:

var group3 = from e in ie group e by e.Department_id xxxxxxxxx Sum xxxxx

How to write this statement? Thanks.

Upvotes: 0

Views: 67

Answers (1)

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34160

var results =  ie.GroupBy(x => x.Department_id).Select(g => g.Sum(x => x.Salary));

 foreach (var item in result)
 {
     Console.WriteLine(result);
 }

OR

ie.GroupBy(x => x.Department_id).Select(g => g.Sum(x => x.Salary))
            .ToList().ForEach(x => Console.WriteLine(x));

Upvotes: 3

Related Questions