简体   繁体   English

LINQ - 包含匿名类型

[英]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. 无法从用法推断出方法'System.Linq.Enumerable.Contains(System.Collections.Generic.IEnumerable,TSource)'的类型参数。 Try specifying the type arguments explicitly. 尝试显式指定类型参数。

I need to filter the first result by COLUMN_B, but I don't know how. 我需要通过COLUMN_B过滤第一个结果,但我不知道如何。 Is there a way to filter it? 有没有办法过滤它?

In order to use Contains you must pass an instance of the type in the IEnumerable<T> . 要使用Contains,必须在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. 相反,我会使用Any扩展方法重载,它允许您指定比较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 尝试使用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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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