Where list contains any in List

1.8k views Asked by At

I am just sending this data to reporting Engine(SSRS) in Asp.net MVC5.
Everything is fine, but this query is taking a lot of time since I have to loop through ListProducts (I guess ListProducts is the size of the database matches).

I am just looking for a way to optimize this query.

I have tried any and contains (as seen below), but they do not seem to work in single table.

context.Products.Where(w => w.ProductDetail.Any(a => a.startDate >= startDate 
                                                     && a.endDate <= endDate))

I got this from here

2)I tried this as well

context.Products.Where(w => ListProducts.Any(x =>w.Contains(x)))

but this also does not work and generates a compile time error that

System.Guid does not contains definition of 'Contains'

Is there any other way, or i am doing it the only correct way?

foreach (var item in ListProducts)
{
    List.AddRange(_context.Products.Where(w => w.ProductId== item).Select(q => new ProductVM
    {
        Name = q.Name,
        Quantity = q.Quantity,

    }).ToList().Select(item=> new ProductVM
    {
             Name = item.Name,
        Quantity = item.Quantity,
    }).ToList());
}


public class Product
{
    public Nullable<System.Guid> ProductId { get; set; }
    public string Name { get; set;}
    public decimal Quantity { get; set; }
}
1

There are 1 answers

11
scgough On BEST ANSWER

Ok, can you do:

var thelist = _context.Products.Where(n => ListProducts.Contains(n.ProductId)).Select(n => new ProductVM
{
     Name = n.Name,
     Quantity = n.Quantity
}).ToList();