简体   繁体   English

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

[英]Using Contains() on Collection of Anonymous Types

I'm still learning LINQ and I have a collection of anonymous types obtained using something like the following. 我还在学习LINQ,我有一些使用以下内容获得的匿名类型的集合。 [mycontext] is a placeholder for my actual data source: [mycontext]是我实际数据源的占位符:

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

How can I use items.Contains() to determine if items contains a matching value? 如何使用items.Contains()来确定items包含匹配值?

The value I am searching for is not an anonymous type. 我要搜索的值不是匿名类型。 So I will need to write my own compare logic, preferably as a lambda expression. 所以我需要编写自己的比较逻辑,最好是作为lambda表达式。

If you prefer to use a predicate then you're probably better off using Any rather than Contains : 如果你更喜欢使用谓词,那么你可能最好使用Any而不是Contains

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

Try the LINQ Any() method: 尝试LINQ Any()方法:

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

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

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

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

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