如何在linq的select语句中使用where子句?(即.)

本文关键字:子句 where linq 语句 select | 更新日期: 2023-09-27 18:18:11

我有这样的linq查询:

var sku = (from a in con.MagentoStockBalances
           join b in con.MFGParts on a.SKU equals b.mfgPartKey
           join c in con.DCInventory_Currents on b.mfgPartKey equals c.mfgPartKey
           where a.SKU != 0 && c.dcKey ==6
           select new
           {
               Part_Number = b.mfgPartNumber,
               Stock = a.stockBalance,
               Recomended = a.RecomendedStock,
               Cato = c.totalOnHandQuantity
           }).ToList();

现在我需要删除c.dkey ==6条件,并有这样的东西:

var sku = (from a in con.MagentoStockBalances
           join b in con.MFGParts on a.SKU equals b.mfgPartKey
           join c in con.DCInventory_Currents on b.mfgPartKey equals c.mfgPartKey
           where a.SKU != 0
           select new
           {
               Part_Number = b.mfgPartNumber,
               Stock = a.stockBalance,
               Recomended = a.RecomendedStock,
               Cato = c.totalOnHandQuantity where c.dcKey == 6,
              Kerry = c.totalOnHandQuantity where c.dcKey == 7
           }).ToList();

如何在linq的select语句中使用where子句?(即.)

像这样:

Cato = c.dcKey == 6 ? c.totalOnHandQuantity : 0,
Kerry = c.dcKey == 7 ? c.totalOnHandQuantity : 0

?:语法称为条件操作符。

与其添加另一个join,不如在let中使用单独的查询:

from a in con.MagentoStockBalances
join b in con.MFGParts on a.SKU equals b.mfgPartKey
where a.SKU != 0
let cs = con.DCInventory_Currents.Where(c => b.mfgPartKey == c.mfgPartKey)
select new
{
    Part_Number = b.mfgPartNumber,
    Stock = a.stockBalance,
    Recomended = a.RecomendedStock,
    Cato = cs.Single(c => c.dcKey == 6).totalOnHandQuantity 
    Kerry = cs.Single(c => c.dcKey == 7).totalOnHandQuantity 
}

虽然我不知道LINQ对SQL处理这样的查询有多好(如果它能处理的话)

var query= from x in context.a 
       where String.IsNullOrEmpty(param1) || (x.p == param1 && x.i == param2)
        select x;