2011-01-19 19 views
0

在下面的LINQ語句中,我試圖選擇人員,但僅當他們的ID出現在另一個表(連接表)中時纔會選擇。我錯過了什麼?只有當他們的ID出現在另一個表中時,我該如何選擇一個人?

在這個例子中,我有一個People表和一個Contractors表。該人的聯繫人ID可能會出現在承包商表格中。我想獲取Contractors表中出現的聯繫人Id。

var allPeople = People.Where(x => x.Contractors 
            .Where(m=> m.ContactID == x.ContactID) 
            .Select(x => x.ContactID)); 

回答

0

Where函數必須返回一個布爾表達式。如果我正確理解你的問題,你只需要來自承包商表中的人民表的人。然後,我們可以問這一點:給我一個人,如果任何承包商有ID:

var allPeople = People.Where(x => x.Contractors 
            .Any(m => m.ContactID == x.ContactID)); 
+0

我開始使用的。任何()但那一點都不不工作。我可能一直在想這個解決方案。謝謝! – DenaliHardtail 2011-01-19 22:52:42

1

如何定期LINQ JOIN聲明:

var peopleWithContact = People.Join(
    Contractors, 
    p => p.ContactId, // the field to join by from People table 
    c => c.ContactId, // the field to join by from Contractors table 
    (p, c) => p.ContactId); // the result if match; could be just p. 
相關問題