Kardon63
Kardon63

Reputation: 346

How to filter IQueryable with an OR statement in a for loop

I am trying to filter a list of products by Color Ids and i want to show all products with this list of colors, and i am applying pagination so that is why i am using IQueryable.

I tried doing such thing but the products result is not getting all the object like:

if (!string.IsNullOrEmpty(productsParams.ColorsId))
        {
            var colorsIds = productsParams.ColorsId.Split(',');
            List<Product> filtredProducts = new List<Product>();

            foreach (var color in colorsIds)
            {
                var productColors = products.Where(c => c.ColorId == int.Parse(color));
                filtredProducts.AddRange(productColors);
            }
            products = filtredProducts.AsQueryable();
        }

but an error is occurring System.InvalidOperationException: The source IQueryable doesn't implement IAsyncEnumerable<YounesCo_Backend.Models.Product>. Only sources that implement IAsyncEnumerable can be used for Entity Framework asynchronous operations.

what can i do to filter my list of products with multiple colors?

Upvotes: 0

Views: 1150

Answers (1)

Ahmad Hamzavi
Ahmad Hamzavi

Reputation: 686

  1. one (And)

    if (!string.IsNullOrEmpty(productsParams.ColorsId))
    {
        var colorsIds = productsParams.ColorsId.Split(',');
        var query = products.AsQueryable() ;
        foreach (var color in colorsIds)
        {
            query = query.Where(c => c.ColorId == int.Parse(color));               
        }
        List<Product> filtredProducts = query.ToList();
    }
    
  2. two (OR)

    if (!string.IsNullOrEmpty(productsParams.ColorsId))
    {
        int[]  colorsIds = ToIntArray(productsParams.ColorsId.Split(','));
        List<Product> filtredProducts = products.Where(c => colorsIds.Contains(c.ColorId)).ToList(); 
    }
    

you must implement ToIntArrat(List list) method, (Convert List<String[]> to Array int[][])

Upvotes: 1

Related Questions