2012-04-18 87 views
3

這是否有一種方法來這些foreach循環只是一個 lambda表達式?如何將這個雙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

你有意說'只是一個lambda'嗎?沒有人提供'只有一個'的答案... – 2012-04-18 17:49:16

+0

我不太明白你的問題。但似乎很多人明白我在問什麼:) – dotnetN00b 2012-04-18 17:55:03

+1

你說一個lambda,這意味着一個=> – 2012-04-18 23:08:19

回答

15
int numOfEvents = eventsForAllMonths.SelectMany(m => m.AllDays) 
            .Select(d => d.CalEvents.Count) 
            .Sum(); 
0

ForEach()爲生,所以:

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

這不是plinq-safe :) – 2012-04-18 17:42:45

+0

和'eventsForAllMonths'可能不是'List' – 2012-04-18 17:43:12

+1

這可能或可能不工作取決於eventsForAllMonths的類型。 ForEach僅適用於列表。如果eventsForAllMonths是其他任何東西,則失敗。 – 2012-04-18 17:43:24

2

試試這個:

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

     return numOfEvents + 1; 
    } 
3
return (eventsForAllMonths.SelectMany(eventMonth => eventMonth.AllDays).Sum(eventDay => eventDay.CalEvents.Count) + 1); 
2

這個怎麼樣?

return 
    (from m in eventsForAllMonths 
    from d in m.AllDays 
    select d.CalEvents.Count).Sum() + 1; 
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(); 
相關問題