Search code examples
linqentity-framework-corevisual-studio-2019where-clausepredicate

Linq to entity with dynamically growing where clause


I am trying to fetch data from an entity based on some criteria. The WHERE clause will have any number of 'OR' conditions. How can I acheive this?

var skill = skillset.split(";"); //array can have any number of items
var EmployeeList1 = EmployeeList
   .Where(x => x.Primary1.ToUpper().Contains(skill[0])         
       || x.Primary2.ToUpper().Contains(skill[0])
       || x.Primary1.ToUpper().Contains(skill[1])                       
       || x.Primary2.ToUpper().Contains(skill[1]))
   .ToList();

return EmpMapper.Mapper.Map<List<EmployeeModel>>(EmployeeList1); 

I need to build an expression for where clause with 'n' number of 'OR' conditions. I tried using predicate, but got exception(Index was outside the bounds of the array.).

    var predicate =  PredicateBuilder.New<ResourceEntity>(true);
    for (int i = 0; i < skill.Count(); i++)
    {
       predicate= predicate.Or(p => p.Primary1.Contains(skill[i]));
    }

Solution

  • You have to copy for variable into local variable:

    var predicate = PredicateBuilder.New<ResourceEntity>(true);
    for (int i = 0; i < skill.Length; i++)
    {
        var s = skill[i];
        predicate = predicate.Or(p => p.Primary1.ToUpper().Contains(s));
        predicate = predicate.Or(p => p.Primary2.ToUpper().Contains(s));
    }