2012-01-18 149 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