shiva1367 shiva1367 - 1 year ago 105
C# Question

sum of one column with condition using linq

I have data table with some columns like this:

e.g :

WorkHour Salary Name
60 100 A
70 120 B
65 105 C

Sum of WorkHour: 195

Sum of Salary : 225

I want sum of columns "WorkHour" and "Salary" but with condition:
If Name==A add WorkHour to sum but not add it's Salary.

Here is my code:

var resultSum = from row in dt.AsEnumerable()
group row by row.Field<string>("UserId") into grp
select new
Salary = grp.Sum(r => r.Field<decimal>("Salary")),
WorkHour = grp.Sum(r => r.Field<decimal>("WorkHour"))

foreach (var rn in resultSum)
decimal dSalary = rn.Salary;
decimal WorkHour = rn.WorkHour;

Answer Source

Group the records and then when calculating the Salary add a Where before the Sum:

var result = (from item in dt.AsEnumerable()
              group item by item.Field<string>("UserId") into g
                  Salary = g.Where(i => i.Field<string>("Name") != "A")
                            .Sum(i => i.Field<decimal>("Salary")),
                  WorkHour = g.Sum(i => i.Field<decimal>("WorkHour"))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download