Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary operator in Linq

Tags:

c#

linq

var result = from payroll in currentMonthPayroll
    select new SalaryDifference
    {
        PreviousMonthSalary = previousMonthPayroll.Where(t => t.EmployeeId == payroll.EmployeeId).FirstOrDefault() == null ?
        default(decimal) : previousMonthPayroll.Where(t => t.EmployeeId == payroll.EmployeeId).FirstOrDefault().Salary,
    };

Is there a way not to repeat the previousMonthPayroll.Where(t => t.EmployeeId == payroll.EmployeeId).FirstOrDefault() logic to pick Salary value?

I tried:

previousMonthPayroll.Where(t => t.EmployeeId == payroll.EmployeeId)
    .FirstOrDefault().Salary ?? default(decimal);

But, if previousMonthPayroll.Where(t => t.EmployeeId == payroll.EmployeeId).FirstOrDefault() is null, it throws exception.

like image 399
Mike Debela Avatar asked May 31 '15 15:05

Mike Debela


2 Answers

You can use Enumerable.DefaultIfEmpty

previousMonthPayroll.Where(t => t.EmployeeId == payroll.EmployeeId)
                    .DefaultIfEmpty(yourDefaultObject)
                    .First();

Where yourDefaultObject is an object with the default salary of default(decimal).

like image 148
user35443 Avatar answered Sep 28 '22 15:09

user35443


You can use the let keyword:

from payroll in currentMonthPayroll
let prevSalary = previousMonthPayroll.FirstOrDefault(t => t.EmployeeId == payroll.EmployeeId)
select new SalaryDifference
{
    PreviousMonthSalary = prevSalary != null ? prevSalary.Salary : default(decimal)
};

See MSDN

like image 35
haim770 Avatar answered Sep 28 '22 15:09

haim770