如何将多个嵌套的foreach组合到Linq查询中

时间:2017-05-25 16:54:28

标签: c# linq foreach

我是linq查询的新手。有没有办法将这些嵌套的foreach合并到一个linq查询中。

如果没有,在这种情况下是否有更好的更新方式?

谢谢

    List<Student> StudentList = new List<Student>();
    List<int> IDsList = new List<int>();


    foreach (var id in IDsList)
    {

        foreach (var st in StudentList.Where(a => a.StudentID == id))
        {
            foreach (var cr in st.Courses)
            {
                cr.Projects.Where(b => string.IsNullOrEmpty(b.ProjectName) == true).ToList().ForEach(c => c.ProjectName = "Dummy");

            }
        }

    }




public class Student
{
    public string FirstName { get; set; }
    public int StudentID { get; set; }
    public List<course> Courses { get; set; }

}

public class course
{
    public int CourseID { get; set; }
    public string Description { get; set; }
    public List<CourseProjects> Projects { get; set; }
}

public class CourseProjects
{
    public string ProjectName { get; set; }
    public int ProjectID { get; set; }

}

2 个答案:

答案 0 :(得分:3)

accept_nested_attributes_for

答案 1 :(得分:1)

您可以使用selectMany替换每个嵌套的foreach。

  StudentList.Where(s => IDsList.Contains(s.StudentID)).SelectMany(f => f.Courses).SelectMany(p => p.Projects).Where(b => string.IsNullOrEmpty(b.ProjectName)).ToList().
            ForEach(c => c.ProjectName = "Dummy");

是否真的是更新列表的更好方法仍有争议。