Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Count of value of nested object by linq [closed]

Tags:

c#

linq

Can anyone please suggest how to get the sum of points from all the Event objects by using linq.

new Category
{
     CategoryId = "NUTR",
     CategoryName = "NUTR",
     CategoryDescription = "NUTR Desc",
     TotalPoints = "100",
     Events = new List<Event>
           {
             new Event{Firstname = "HELEN",Surname = "BECKETT", 
                 Points = "10", Description = "NUTR Desc",Eventdate = "2013/04/19",EntityNumber = "1203206956"},
             new Event{Firstname = "PAUL",Surname = "BECKETT", 
                 Points = "90", Description = "NUTR Desc",Eventdate = "2013/06/19",EntityNumber = "1203206957"}
           }
}
like image 630
Soni Avatar asked Oct 20 '25 05:10

Soni


1 Answers

You need to use SelectMany to flatten the list of events, then do the sum:

var totalPoints = categories
    .SelectMany(c => c.Events)
    .Sum(e => Convert.ToInt32(e.Points));
like image 118
Mahmoud Gamal Avatar answered Oct 22 '25 03:10

Mahmoud Gamal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!