tec
tec

Reputation: 35

How to get sum of values dynamically to different variable in c#

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

Answers (3)

Denis Bubnov
Denis Bubnov

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:

  1. level(1) = 3
  2. level(2) = 4
  3. level(3) = 9

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

cuongle
cuongle

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

Ren&#233; Vogt
Ren&#233; Vogt

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 Levels as keys and the sum of the corresponding sals as value.

Upvotes: 1

Related Questions