Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Contains() on Collection of Anonymous Types

Tags:

c#

contains

linq

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.

like image 637
Jonathan Wood Avatar asked Jan 20 '23 10:01

Jonathan Wood


2 Answers

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);
like image 168
LukeH Avatar answered Jan 30 '23 03:01

LukeH


Try the LINQ Any() method:

if (items.Any(i => i.col1 == myOtherThing.Value))
{
    // Effectively Contains() == true
}
like image 20
Ed Chapel Avatar answered Jan 30 '23 04:01

Ed Chapel