如何将这个双 foreach 循环转换为 lambda

本文关键字:循环 转换 lambda foreach | 更新日期: 2023-09-27 18:31:36

有没有办法让这些 foreach 循环只有一个 lambda 表达式?

    private int getNextEventId()
    {
        int numOfEvents = 0;
        foreach (MonthModel eventMonth in eventsForAllMonths)
        {
            foreach (DayModel eventDay in eventMonth.AllDays)
            {
                numOfEvents += eventDay.CalEvents.Count;
            }
        }
        return numOfEvents + 1;
    }

如何将这个双 foreach 循环转换为 lambda

int numOfEvents = eventsForAllMonths.SelectMany(m => m.AllDays)
                                    .Select(d => d.CalEvents.Count)
                                    .Sum();
return (eventsForAllMonths.SelectMany(eventMonth => eventMonth.AllDays).Sum(eventDay => eventDay.CalEvents.Count) + 1);

试试这个:

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

这个怎么样?

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

ForEach()为生,所以:

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

在 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();