按内部列表键过滤列表

时间:2012-01-18 11:29:49

标签: c# list

我有一个List<Student>

的列表对象
Student
    StudentId
    StudentName
    List<Subject>
Subject
    SubjectId
    SubjectName

如何按List<Student>过滤SubjectId来回复学生的主题。

我在名单上的是

Student1
    Math { SubjectId = 1 }
    Science { SubjectId = 2 }
    Speech { SubjectId = 3 }
Student2
    Math { SubjectId = 1 }
    Cheering { SubjectId = 4 }
Student3
    Science { SubjectId = 2 }
    Speech { SubjectId = 4 }

我想通过SubjectId = 1过滤上面的对象,并希望返回一个像

这样的对象
Student1
    Math { SubjectId = 1 }
Student2
    Math { SubjectId = 1 }

如何在C#上查询?

3 个答案:

答案 0 :(得分:1)

这样的事情怎么样?

students.Where(s => s.Subjects.Any(su => su.SubjectId = 1));

答案 1 :(得分:1)

var result = (from s in students
          where s.Subjects.Any(subj => subj.SubjectID == yourValue)
          select new Student
          {
              Name = s.StudentName
              Subjects = s.Subjects.Where(subj => subj.SubjectID == yourValue).ToList());    
          }

像这样的东西(没有太多检查),它可以做得更好肯定

答案 2 :(得分:0)

var x = from stu in students
        from sub in stu.Subjects
        where sub.SubjectId = 1
        select stu;

我还没有测试,因为我这里没有VS.