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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With