Using Contains () for a collection of anonymous types

I am still learning LINQ, and I have a collection of anonymous types obtained using 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 an appropriate value?

The value I'm looking for is not anonymous. So I will need to write my own comparison logic, preferably as a lambda expression.

+4
source share
3 answers

If you prefer to use a predicate, you are probably better off using Any rather than Contains :

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

Try the LINQ Any() method:

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

Or you can use the Any method with a predicate.

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

All Articles