How to convert this double foreach loop only in lambdas?

Is there a way for these foreach loops to only have one lambda expression?

    private int getNextEventId()
    {
        int numOfEvents = 0;

        foreach (MonthModel eventMonth in eventsForAllMonths)
        {
            foreach (DayModel eventDay in eventMonth.AllDays)
            {
                numOfEvents += eventDay.CalEvents.Count;
            }
        }

        return numOfEvents + 1;
    }
+3
source share
6 answers
int numOfEvents = eventsForAllMonths.SelectMany(m => m.AllDays)
                                    .Select(d => d.CalEvents.Count)
                                    .Sum();
+15
source
return (eventsForAllMonths.SelectMany(eventMonth => eventMonth.AllDays).Sum(eventDay => eventDay.CalEvents.Count) + 1);
+3
source

Try the following:

    private int getNextEventId()
    {
        int numOfEvents = eventsForAllMonths.SelectMany(eventMonth => eventMonth.AllDays).Aggregate(0, (current, eventDay) => current + eventDay.CalEvents.Count);

        return numOfEvents + 1;
    }
+2
source

How about this?

return
    (from m in eventsForAllMonths
    from d in m.AllDays
    select d.CalEvents.Count).Sum() + 1;
+2
source

I ForEach()for life, therefore:

eventsForallMonths.ForEach(em=>em.ForEach(ed=>numOfEvents+=ed.CalEvents.Count));
0
source

How to convert this to lambda?

List<Item> listItem = new List<Item>();
foreach (StackPanel sp in spPhotos.Children)
{
    foreach(Item item in sp.Children)
    {
        listItem.Add(item);
    }
    sp.Children.Clear();
}
spPhotos.Children.Clear();
0
source

All Articles