Linq是否有办法根据不同的条件应用不同的计算方法

时间:2009-06-02 03:31:01

标签: c# linq

我正在尝试找出正确的语法以使其正常工作。这是一个例子。你能纠正它/将其翻译成linq语法吗?

      From p In products() 
      group p by p.Category into g 
      select new { Category = g.Key, 
                   TotalUnitsInStock = if(g.key="b", g.Avg(p => p.UnitsInStock),
                                          g.Sum(p => p.UnitsInStock))

在此示例中,产品将是数据表。谢谢。

2 个答案:

答案 0 :(得分:3)

from p in products()
group p by p.Category into g
select new
{
    Category = g.Key,
    TotalUnitsInStock = g.Key == "b"
        ? g.Average(p => p.UnitsInStock)
        : g.Sum(p => p.UnitsInStock)
}

答案 1 :(得分:2)

尝试以下

  var query = from p In products() 
              group p by p.Category into g 
              select new { Category = g.Key, 
                  TotalUnitsInStock = (g.key=="b") ? g.Avg(p => p.UnitsInStock) :
                                      g.Sum(p => p.UnitsInStock));