Alan2
Alan2

Reputation: 24592

How can I get a total count of an int field in a List?

I have this class, variable and method used to populate it:

public class CategoryGroupWordCountVM : ObservableProperty
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool IsToggled { get; set; }
    public int TotalWordCount { get; set; }
}

List<CategoryGroupWordCountVM> categoryGroups;

categoryGroups = AS.dm.GetCategoryGroupWithWordCount();

How can I get a total of all of the values of the TotalWordCount field using LINQ or any other method if it can be done as a one liner. I know I can do this with a "for" loop but hoping for something that could be all in one line.

Upvotes: 0

Views: 621

Answers (2)

Roxy&#39;Pro
Roxy&#39;Pro

Reputation: 4454

You can do LINQ to Objects and the use LINQ to calculate the totals:

decimal totalSum = (from od in categoryGroups
select od.TotalWordCount ).Sum();

You can also use lambda-expressions to do this, which is a bit "cleaner".

decimal totalSum  = categoryGroups.Sum(x => x.TotalWordCount);

Upvotes: 1

Sajeetharan
Sajeetharan

Reputation: 222722

Use Linq,

var sum = categoryGroups.Sum(x=>x.TotalWordCount);

Upvotes: 3

Related Questions