Search code examples
c#lambdafunctional-programming

C# lambda expression to select elements


I have a list of categories (string) and a list of objects of a certain type. I need to select from this list of objects only those which a property is in my list of categories.

I'm trying to use a lambda expression inside the Where method. I also tried to use the in operator but I got the following error messages:

Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type.

Cannot implicitly convert type 'string' to 'bool'

var entries = programmes.Where(x => x.Program.Name in categories);

I expect to return a sub-list with the objects which attribute Name is a member of my list categories.


Solution

  • You can use Contains in this case

    var entries = programmes.Where(x => categories.Contains(x.Program.Name)).ToList();
    

    select only elements the x.Program.Name is in to categories list