Home > OS >  How to dynamically add "OR" conditions in Where method provided by Entity Framework
How to dynamically add "OR" conditions in Where method provided by Entity Framework

Time:01-17

I have a list of Ids and I want to fetch those records from my Products table (present in database) where Product Id matches to any Ids given in the following list.

List<int> ids = new List<int> { 1, 2, 3 };

I know I can do like this ->

_unitOfWork.Product.GetAll(p => p.Id == 1 || p.Id == 2 || p.Id == 3);

But problem with this is my list is dynamic. Here just for example I hard coded 3 values but it could be the list of n numbers. So in that case it will fail.

So, I want to know if there a way to or condition like ->

_unitOfWork.Product.GetAll(p => p.Id == //all ids present in list with OR conditions, something like foreach loop which will iterate through my list of ids & internally will make condition like I made above with hard coded values);

I am using repository pattern in my project, hence my GetAll() method looks like this:

public IEnumerable<T> GetAll(Expression<Func<T, bool>>? filter = null, string? includeProperties = null)
{
    IQueryable<T> query = dbSet;

    if (filter != null)
    {
        query = query.Where(filter);
    }

    if (includeProperties != null)
    {
        query = IncludeProperties(query,includeProperties);
    }

    return query.ToList();
}

CodePudding user response:

you can use the Contains method along with the In operator to filter records based on a list of IDs. Here's an example of how you can do this using Linq:

_unitOfWork.Product.GetAll(p => ids.Contains(p.Id));

This will generate a query that will return all products where the Id property matches any of the IDs in the ids list.

Alternatively, you can use the Any method to accomplish the same thing:

_unitOfWork.Product.GetAll(p => ids.Any(i => i == p.Id));

This will also generate a query that will return all products where the Id property matches any of the IDs in the ids list.

CodePudding user response:

You can use .Any(),

List<int> ids = new List<int> { 1, 2, 3 };
_unitOfWork.Product.GetAll(p => ids.Any(x => x == p.Id));

Alternate way you can also use .Contains()

_unitOfWork.Product.GetAll(p => ids.Contains(p.Id));
  • Related