簡體   English   中英

LINQ而不是嵌套的foreach和if

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM