linq - 转换嵌套的foreach循环

时间:2011-10-18 11:07:43

标签: linq

尝试将foreach循环转换为linq时遇到问题:

IList<DateTime> dicommentdates = new List<DateTime>();

foreach (DiaryEntry dEnt in DiaryEntries)
{
    if (dEnt.EnteredInYearGroup == this.YearGroup)
    {
        foreach (DiaryEntryComment dcom in dEnt.DiaryEntryComments)
        {
            //add all the comments for this year group
            dicommentdates.Add(dcom.DateEntered);
        }
    }
}

任何帮助都非常感激。

5 个答案:

答案 0 :(得分:3)

试试这个:

List<DateTime> diCommentDates = DiaryEntries.Where(dEnt => dEnt.EnteredInYearGroup == this.YearGroup)
                                            .SelectMany(dEnt => dEnt.DiaryEntryComments)
                                            .Select(dCom => dCom.DateEntered)
                                            .ToList();

答案 1 :(得分:2)

 IList<DateTime> dicommentdates = DiaryEntries
               .Where( x=> x.EnteredInYearGroup == this.YearGroup)
               .SelectMany(x => x.DiaryEntryComments)
               .Select(x => x.DateEntered)
               .ToList()

答案 2 :(得分:2)

这应该这样做:

IList<DateTime> dicommentdates =
    (
        from dEnt in DiaryEntries
        where dEnt.EnteredInYearGroup == this.YearGroup
        from dcom in dEnt.DiaryEntryComments
        select dcom.DateEntered
    ).ToList();

答案 3 :(得分:1)

以下内容应该有效:

dicommentdates.AddRange(
   DiaryEntries.Where(dEnt => dEnt.EnteredInYearGroup == this.YearGroup)
   .SelectMany(dEnt => dEnt.DiaryEntryComments)).Select(dcom=> dcom.DateEntered);

答案 4 :(得分:1)

我认为,最简单的形式是:

var dates = 
    from entry in DiaryEntries 
    where entry.YearGroup == YearGroup 
    select entry.DiaryEntryComments.DateEntered;