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.
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)
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With