[英]LINQ instead of nested foreach and if
有誰知道Linq代碼用於以下代碼?:
foreach (Bed bed in field.GetBeds())
{
foreach (Asparagus asparagus in bed.GetAsparaguses())
{
if (asparagus.Time.Date == day.Date && asparagus.Harvested)
{
count++;
}
}
}
訣竅是使用SelectMany
展平嵌套項目。
var count = field.BetBeds()
.SelectMany(bed => bed.GetAsparaguses())
.Where(asparagus => asparagus.Time.Date == day.Date && asparagus.Harvested)
.Count();
通過SelectMany
來獲取所有蘆筍,並根據“ Where
和“ Count
結果”中的條件對其進行過濾
field.GetBeds()
.SelectMany(bed => bed.GetAsparaguses())
.Where(asparagus => asparagus.Time.Date == day.Date && asparagus.Harvested)
.Count();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.