LINQ - Contains with anonymous type

When using this code (simplified for query):

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; 

I got the following error:

Type arguments for the method 'System.Linq.Enumerable.Contains (System.Collections.Generic.IEnumerable, TSource)' cannot be inferred from Application. Try to specify the type of the arguments explicitly.

I need to filter out the first result of COLUMN_B, but I don't know how to do it. Is there any way to filter it?

+4
source share
3 answers

To use Contains, you must pass an instance of the type in IEnumerable<T> . This is extremely complicated with anonymous types.

Instead, I would use an overload of the Any extension method, which allows you to specify a comparative lambda. for instance

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

Try using

 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; 
+1
source

it works?

 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
source

Source: https://habr.com/ru/post/1304393/


All Articles