Sreedhar
Sreedhar

Reputation: 30035

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

I'm trying to figure out the correct syntax to make it work. Here's an example. Could you correct it/translate it into 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))

Products would be a datatable in this example. Thanks.

Upvotes: 3

Views: 235

Answers (2)

Bryan Watts
Bryan Watts

Reputation: 45465

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

Upvotes: 3

JaredPar
JaredPar

Reputation: 755141

Try the following

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

Upvotes: 2

Related Questions