How to make an if in linq

1

How can I make a if within Linq for example I have the code:

lstParentLines = dbContext.Packages.Select(p => new SummaryViewModel
{ 
    Id = p.Id,
    Package = p.Name,
    CurrentTotal = budgMonthDetails.Where(bm => bm.CostCenterId == costCenterId     &&).Sum(bm => (decimal?)bm.Total) ?? 0,
    PreviousForecast = budgMonthDetails
                       .Where(bm => bm.CostCenterId == costCenterId )
                       .Sum(bm => (decimal?)bm.Forecast) ?? 0,
    VarTotalVSFrcst = (decimal?)(budgMonthDetails
                       .Where(bm => bm.CostCenterId == costCenterId)
                       .Sum(bm => (decimal?)bm.Total) ?? 0) /  ((budgMonthDetails.Where(bm => bm.CostCenterId == costCenterId).Sum(bm => bm.Forecast))) ?? 0
}).ToList();

So if bm.Total is zero the division is: bm.Forecast between bm.Total

But if bm.Total is greater than zero, the division is: bm.Total between bm.forecast

    
asked by waldemar 30.09.2016 в 20:19
source

2 answers

2

Use the full syntax for lambda

//...
.Select(x => 
{
    var model = new Model();

    if (<condicion>) 
    {
        model.Total = // Lo que necesites
    }

    return model;
});

Notice that in addition to the symbol => I'm also using { } and return .

Lambda are regular methods with the detail that there is an abbreviated form that is the most used.

 x => x * x

Equivalent to

x =>
{
    // aquí puede haber más código
    return x * x;
}
    
answered by 30.09.2016 в 20:48
0

the syntax would be this:

if (condicionACumplir)
    variable = variable.Where(p => p.At == At);

Your code would look something like this:

if(bm.Total==0)
   VarTotalVSFrcst = bm.Forecast/bm.Total;

if(bm.Total>0)
   VarTotalVSFrcst = bm.Total/bm.Forecast;

answered by 30.09.2016 в 20:45