如何在linq的select语句中使用where子句。 (即在财产上。)

时间:2013-06-13 18:33:46

标签: c# linq linq-to-sql

我有这个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.dcKey == 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();

3 个答案:

答案 0 :(得分:6)

这样的事情:

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

?:语法称为条件运算符。

答案 1 :(得分: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 to SQL如何处理这样的查询(如果它完全处理它)。

答案 2 :(得分:-1)

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