3

有没有办法让这些 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;
    }
4

6 回答 6

15
int numOfEvents = eventsForAllMonths.SelectMany(m => m.AllDays)
                                    .Select(d => d.CalEvents.Count)
                                    .Sum();
于 2012-04-18T17:41:44.610 回答
3
return (eventsForAllMonths.SelectMany(eventMonth => eventMonth.AllDays).Sum(eventDay => eventDay.CalEvents.Count) + 1);
于 2012-04-18T17:45:16.507 回答
2

试试这个:

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

        return numOfEvents + 1;
    }
于 2012-04-18T17:44:39.067 回答
2

这个怎么样?

return
    (from m in eventsForAllMonths
    from d in m.AllDays
    select d.CalEvents.Count).Sum() + 1;
于 2012-04-18T18:29:55.627 回答
0

ForEach()以谋生为生,所以:

eventsForallMonths.ForEach(em=>em.ForEach(ed=>numOfEvents+=ed.CalEvents.Count));
于 2012-04-18T17:41:31.053 回答
0

如何在 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();
于 2012-12-15T21:18:12.207 回答