Reputation: 35
I have an object (Details
) which is having employee details. That object has properties (sal
and Level
).
I just want to get the sum of sal
for each and every Level
.
foreach (var emp in Details)
{
int empsal=emp.sal;
int empLevel= emp.Level;
}
example: I want the sum of all employee sal into different variables based on the levels.
Upvotes: 2
Views: 1502
Reputation: 2785
The first answer is good. For example you have class:
public class Details
{
public int Level { get; set; }
public int Sal { get; set; }
}
and you have data:
var data = new List<Details>()
{
new Details() {Level = 1, Sal = 1},
new Details() {Level = 1, Sal = 1},
new Details() {Level = 1, Sal = 1},
new Details() {Level = 2, Sal = 2},
new Details() {Level = 2, Sal = 2},
new Details() {Level = 3, Sal = 3},
new Details() {Level = 3, Sal = 3},
new Details() {Level = 3, Sal = 3},
};
if we calculate, we get:
Solution one (good):
var sum = data.GroupBy(x => x.Level).ToDictionary(x => x.Key, a => a.Sum(b => b.Sal));
Console.WriteLine(sum[1]); // result 3
Console.WriteLine(sum[2]); // result 4
Console.WriteLine(sum[3]); // result 9
Solution two (not very good):
public int GetSumOfLevel(int level, List<Details> details)
{
return details.Where(x => x.Level == level).Sum(x => x.Sal);
}
...
Console.WriteLine(GetSumOfLevel(1, data)); // result 3
Console.WriteLine(GetSumOfLevel(2, data)); // result 4
Console.WriteLine(GetSumOfLevel(3, data)); // result 9
May be choose the first option?
Upvotes: 0
Reputation: 75306
var sumByLevels = Details.GroupBy(employee => employee.Level)
.ToDictionary(g => g.Key, g => g.Sum(x => x.sal));
Now assume you want to get total salary of level 1:
var result = sumByLevels[1];
Upvotes: 2
Reputation: 43876
You can do that using LINQ's GroupBy
method:
Dictionary<int, int> sumsByLevel =
Details.GroupBy(employee => employee.Level, employee => employee.sal).
ToDictionary(group => group.Key, group => group.Sum());
This results in a dictionary with the Level
s as keys and the sum of the corresponding sal
s as value.
Upvotes: 1