有人知道以下代码的Linq代码是什么吗?:
foreach (Bed bed in field.GetBeds())
{
foreach (Asparagus asparagus in bed.GetAsparaguses())
{
if (asparagus.Time.Date == day.Date && asparagus.Harvested)
{
count++;
}
}
}
答案 0 :(得分:4)
诀窍是使用SelectMany
展平嵌套项目。
var count = field.BetBeds()
.SelectMany(bed => bed.GetAsparaguses())
.Where(asparagus => asparagus.Time.Date == day.Date && asparagus.Harvested)
.Count();
答案 1 :(得分:1)
通过SelectMany
获取所有芦笋,并按Where
和Count
中的条件对其进行过滤
field.GetBeds()
.SelectMany(bed => bed.GetAsparaguses())
.Where(asparagus => asparagus.Time.Date == day.Date && asparagus.Harvested)
.Count();