在匿名类型集合上使用Contains()

时间:2011-06-20 23:09:50

标签: c# linq contains

我还在学习LINQ,并且我使用以下内容获得了一系列匿名类型。 [mycontext]是我实际数据源的占位符:

var items = from item in [mycontext]
            select new { item.col1, item.col2, item.col3 };

如何使用items.Contains()确定items是否包含匹配值?

我要搜索的值是不是匿名类型。所以我需要编写自己的比较逻辑,最好是作为lambda表达式。

3 个答案:

答案 0 :(得分:4)

如果您更喜欢使用谓词,那么您最好使用Any而不是Contains

bool exists = items.Any(x => x.col1 == "foo"
                             && x.col2 == "bar"
                             && x.col3 == 42);

答案 1 :(得分:3)

尝试使用LINQ Any()方法:

if (items.Any(i => i.col1 == myOtherThing.Value))
{
    // Effectively Contains() == true
}

答案 2 :(得分:2)

或者您可以将“Any”方法与谓词一起使用。

bool exists = items.Any( i => {logic} );