2010-03-17 154 views
4

使用此代碼時(簡化問):LINQ - 包含與匿名類型

var rows1 = (from t1 in db.TABLE1 
    where (t1.COLUMN_A == 1) 
    select new { t1.COLUMN_B, t1.COLUMN_C }); 

var rows2 = (from t2 in db.TABLE2 
    where (rows1.Contains(t2.COLUMN_A)) 
    select t2; 

我得到了以下錯誤:

The type arguments for method 'System.Linq.Enumerable.Contains(System.Collections.Generic.IEnumerable, TSource)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

我需要COLUMN_B篩選的第一個結果,但我不知道如何。有沒有過濾它的方法?

回答

8

爲了使用包含,您必須在IEnumerable<T>中傳遞該類型的實例。匿名類型非常困難。

相反,我會使用Any擴展方法重載,它允許您指定一個比較lambda。例如

var rows2 = (from t2 in db.TABLE2 
    where (rows1.Any(x => x.COLUMN_B == t2.COLUMN_A)) 
    select t2; 
+0

謝謝。有用! – Marlos 2010-03-17 19:12:55

1

嘗試使用任何

var rows1 = (from t1 in db.TABLE1 
    where (t1.COLUMN_A == 1) 
    select new { t1.COLUMN_B, t1.COLUMN_C }); 

var rows2 = (from t2 in db.TABLE2 
    where (rows1.Any(r => r.COLUMN_B == t2.COLUMN_A)) 
    select t2; 
0

這樣做的工作?

var rows1 = (from t1 in db.TABLE1 
    where (t1.COLUMN_A == 1) 
    select new { t1.COLUMN_B, t1.COLUMN_C }).ToList(); 

var rows2 = (from t2 in db.TABLE2 
    where (rows1.Contains(t2.COLUMN_A)) 
    select t2; 
+0

不在這裏,但謝謝。 – Marlos 2010-03-17 19:12:29