我正在尝试编写一个查询,其中将包含基于输入变量的两个条件之一:
!(from o in db.Products.Where(x => x.Company_ID == cid && x.IsDeleted != true)
或
(from o in db.Products.Where(x => x.Company_ID == cid && x.IsDeleted != true)
针对前一种情况,我目前的方法如下。我已经包括了 productExists,它将是确定我是否需要上面的条件 #1 或 #2 的参数。
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
}
}
如果有人能帮我解决这个问题,我将不胜感激。
最佳答案
可能是这样的:
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)
)
你也可以这样做:
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)
)
两个查询将产生相同的 sql
关于c# - 基于 bool 值重新使用 LINQ 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9941581/