2010-07-13 18 views
1

我需要1個表中的字段,而不是1個屬性匹配另一個表中的行。 我可以寫在SQL這個查詢與子查詢這樣:如何返回LINQ中依賴聯接/子查詢的表?

SELECT * 
FROM Table1 
WHERE Property1 IN 
(
    SELECT Property1 
    FROM Table2 
    WHERE Property0 = 1 
) 

但我讀here,它是那麼複雜,也很容易用一個連接來寫,我做到了。但是,到目前爲止,我無法僅返回Table1,因爲我使用了一個連接,如果我沒有弄錯,需要我創建這個匿名類型,如下所示。我在這裏所做的工作(我創建了另一個具有Table1相同屬性的對象),但我不禁想到有更好的方法來做到這一點。

Table1.Join(Table2, t1 => t1.Property1, t2 => t2.Property1, (t1, t2) => new 
{ 
    t1.Property1, 
    t1.Property2, 
    t1.Property3 
}) 
.Select(ob => new UnnecessaryObject 
{ 
    Property1 = ob.Property1, 
    Property2 = ob.Property2, 
    Property3 = ob.Property3 
} 

我也試過只是創造的。選擇部分表1,但我沒有被允許大約明確建設一個錯誤。

只是爲了澄清,我希望能夠返回Table類型的IQueryable,它似乎我應該能夠做到而不必創建UnnecessaryObject ...但我仍然很新LINQ,所以我會很感激你能提供的任何幫助。提前致謝。

回答

3

你可能只是做:

from t1 in table1 
join t2 in table2 on t1.property1 equals t2.property1 
select t1; 

,將返回table1的對象的集合。這從您的示例中假設table1是table1對象的集合,table2是table2對象的集合。

+0

工作太棒了!非常感謝! – Andy 2010-07-14 14:09:11

2

我可以拿出你的原始查詢的最好的翻譯是:

from item in context.Table1 
where context.Table2 
    .Where(x => x.Property0 == 0) 
    .Any(x => x.Property1 == item.Property1) 
select item 

這從Table1,那裏有來自Table2

它還可以選配Property1Property0 == 0是一個項目可以選擇所有項目確實可以通過連接來解決。要獲得有效的連接,您需要在兩個表之間建立關係。然後,你可以不喜歡假設關係稱爲RelatedItems

from item in context.Table1 
join relatedItem in item.RelatedItems 
    on item.Property1 equals relatedItem.Property 
where relatedItem.Property0 == 0 

select item 

這相當於SQL:

SELECT * 
FROM Table1 
JOIN Table2 ON Table1.Property1 = Table2.Property1 
WHERE Table2.Property0 = 0 
+0

工作很好!非常感謝! – Andy 2010-07-14 14:10:16