I'm still learning LINQ and I have a collection of anonymous types obtained using something like the following. [mycontext] is a placeholder for my actual data source:
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?
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.
If you prefer to use a predicate then you're probably better off using Any
rather than Contains
:
bool exists = items.Any(x => x.col1 == "foo"
&& x.col2 == "bar"
&& x.col3 == 42);
Try the LINQ Any()
method:
if (items.Any(i => i.col1 == myOtherThing.Value))
{
// Effectively Contains() == true
}
或者您可以将“Any”方法与谓词一起使用。
bool exists = items.Any( i => {logic} );
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.