Reusing a LINQ query based on a bool value

I am trying to write one query that will include one of two conditions based on an input variable:

!(from o in db.Products.Where(x => x.Company_ID == cid && x.IsDeleted != true)

      

or

(from o in db.Products.Where(x => x.Company_ID == cid && x.IsDeleted != true)

      

My current method, covering the former condition, looks like this. I've included productExists, which will be a parameter that determines if I need condition # 1 or # 2 from above.

public IQueryable<ProductImportViewModel> AllImports(int id, bool productExists)
{
    return (from t1 in db.Products_Staging
            where (t1.ImportFileId == id) && !(from o in db.Products.Where(x => x.Company_ID == cid && x.IsDeleted != true)
                                               select o.ProductName).Contains(t1.ProductName)
            select new ProductImportViewModel
            {
                Id = t1.Id
            }
}

      

If anyone could help me, I would be very grateful.

+3


source to share


1 answer


Something like this could be:

where (t1.ImportFileId == id) && 
            (
                productExists==true
                &&
                !(from o in db.Products.Where(x => x.Company_ID == cid && x.IsDeleted != true).
                                                Select(o=> o.ProductName).Contains(t1.ProductName)
            )
            ||
            (
                productExists==false
                &&
                (from o in db.Products.Where(x => x.Company_ID == cid && x.IsDeleted != true).
                                                Select(o=> o.ProductName).Contains(t1.ProductName)
            )

      

You can also do it something like this:



var query=(from o in db.Products
          .Where(x => x.Company_ID == cid && x.IsDeleted != true).
          Select(o=> o.ProductName);
------
where (t1.ImportFileId == id) && 
    (
        productExists && !query.Contains(t1.ProductName)
    )
    ||
    (
        !productExists && query.Contains(t1.ProductName)
    )

      

Both queries will result in the same sql

+2


source







All Articles