Is there a way in Linq to apply different calculations based on different conditions

I am trying to figure out the correct syntax to make it work. Here is an example. Could you fix or translate it to linq syntax?

      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))

In this example, the products will be data. Thank you

+3
source share
2 answers

Try to execute

  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));
+2
source
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)
}
+3
source

Source: https://habr.com/ru/post/1709568/


All Articles