Reputation: 67283
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.
Upvotes: 5
Views: 2996
Reputation: 7631
Or you could use the "Any" method with a predicate.
bool exists = items.Any( i => {logic} );
Upvotes: 2
Reputation: 269528
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);
Upvotes: 4
Reputation: 6932
Try the LINQ Any()
method:
if (items.Any(i => i.col1 == myOtherThing.Value))
{
// Effectively Contains() == true
}
Upvotes: 3