这有一种方法可以将这些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;
}
答案 0 :(得分:15)
int numOfEvents = eventsForAllMonths.SelectMany(m => m.AllDays)
.Select(d => d.CalEvents.Count)
.Sum();
答案 1 :(得分:3)
return (eventsForAllMonths.SelectMany(eventMonth => eventMonth.AllDays).Sum(eventDay => eventDay.CalEvents.Count) + 1);
答案 2 :(得分:2)
试试这个:
private int getNextEventId()
{
int numOfEvents = eventsForAllMonths.SelectMany(eventMonth => eventMonth.AllDays).Aggregate(0, (current, eventDay) => current + eventDay.CalEvents.Count);
return numOfEvents + 1;
}
答案 3 :(得分:2)
这个怎么样?
return
(from m in eventsForAllMonths
from d in m.AllDays
select d.CalEvents.Count).Sum() + 1;
答案 4 :(得分:0)
我以ForEach()
为生,所以:
eventsForallMonths.ForEach(em=>em.ForEach(ed=>numOfEvents+=ed.CalEvents.Count));
答案 5 :(得分: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();