简体   繁体   中英

LINQ - Contains with anonymous type

When using this code (simplified for asking):

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:

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.

I need to filter the first result by COLUMN_B, but I don't know how. Is there a way to filter it?

In order to use Contains you must pass an instance of the type in the IEnumerable<T> . This is exceedingly hard with anonymous types.

Instead I would use the Any extension method overload which allows you to specify a comparison lambda. For example

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

Try using Any

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;

does this 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM