Search code examples
c#entity-frameworklinqlinq-to-entities

Dynamic Where Clause in LINQ Syntax error


I am trying to build a dynamic WHERE clause in my LINQ statement, however I have encountered some problems.

At the moment I have the following:-

string[] types = typeId[0].Split(','); //contains string array like {"1,2,3"}
marketing = marketing.Where( type => types.Contains(type.TypeID)).ToList();

Can anyone tell me the correct syntax to achieve this?

Thanks


Solution

  • From your error message, type.TypeID is an int.

    So you basically have 2 options:

    Option 1: convert types to int[]:

    int[] types = typeId[0].Split(',').Select(id => int.Parse(id)).ToArray();
    marketing = marketing.Where( type => types.Contains(type.TypeID)).ToList();
    

    Option 2: convert type.TypeID to string:

    string[] types = typeId[0].Split(',');
    marketing = marketing.Where( type => types.Contains(type.TypeID.ToString())).ToList();