LINQ而不是嵌套的foreach和if

时间:2018-09-17 13:22:18

标签: c# linq

有人知道以下代码的Linq代码是什么吗?:

foreach (Bed bed in field.GetBeds())
{
    foreach (Asparagus asparagus in bed.GetAsparaguses())
    {
        if (asparagus.Time.Date == day.Date && asparagus.Harvested)
        {
            count++;
        }
    }
}

2 个答案:

答案 0 :(得分:4)

诀窍是使用SelectMany展平嵌套项目。

var count = field.BetBeds()
    .SelectMany(bed => bed.GetAsparaguses())
    .Where(asparagus => asparagus.Time.Date == day.Date && asparagus.Harvested)
    .Count();

答案 1 :(得分:1)

通过SelectMany获取所有芦笋,并按WhereCount中的条件对其进行过滤

field.GetBeds()
     .SelectMany(bed => bed.GetAsparaguses())
     .Where(asparagus => asparagus.Time.Date == day.Date && asparagus.Harvested)
     .Count();