-1

Am having a list object. i need to add the values in the object in a single line of code without using foreach or for loop. Is it possible using the linq query??

For eg: am having a list object userCount of length 2. I need to find the TotalManagerCount by adding the ManagerCount values in the list.

public class UserCount
{
public int ManagerCount {get; set;}
public int EngineerCount {get; set;}
}

List<UserCount> userCount = new List<UserCount>();

int TotalManagerCount = ??
int TotalEngineerCount = ??

Thanks in advance

Dinesh.

Dinesh M
  • 1,026
  • 8
  • 23

2 Answers2

3

Use LINQ Sum function:

int TotalManagerCount = userCount.Sum(x=>x.ManagerCount);
int TotalEngineerCount = userCount.Sum(x=>x.EngineerCount);
Samvel Petrosov
  • 7,580
  • 2
  • 22
  • 46
1

Use Sum function of Linq

int TotalManagerCount = userCount.Sum(item => item.ManagerCount);
int TotalEngineerCount = userCount.Sum(item => item.EngineerCount);
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396