2012-01-18 170 views
0

名单我有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#?

回答

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());  
      } 

像这样(没有太多的检查),这是可以做到更好的为确保

+0

这看起来更接近我需要的东西,我现在正在测试这一个。 –

1

这样的事情呢?

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

谢谢,我会试试.. –

+0

在这里已经编写了一些属性/变量名称 - 可能需要调整。 –

+2

就像来自Wint的那个......你会给他所有的主题,但它看起来像他只想要他正在寻找的那个 –

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

我没有测试但因为我这儿没VS。

+0

这会给他所有的科目,但看起来他只想要符合条件的那个 –

+0

是的,你是对的。我可能会使用2个查询子句来完成这个任务。一个查询困扰我。 – Wint