Search code examples
linq

A way to bypass LINQ queryable NullReferenceException?


I have a query which is supposed to sum up the hours and pay for each individual user from a specific list. To calculate the total pay, I multiply each instance of hour entries by an instance of an instance of a salary.

The problem is, that sometimes, the salary can return as null, which is intentional. In that case, I'd like to return a 0 instead of a null, however I cannot figure out how to do it.

Here is the query:

time.GroupBy(x => x.User).Select(z => new
{
   User = string.Format("{0} {1}", z.Key.Users.Name, z.Key.Users.Surname),
   Hours = z.Sum(x => x.Hours),
   TotalPay = z.Sum(x => x.Hours * (double?)salaries.Where(y => y.User.Id == x.User.Id && y.Date <= x.Date).OrderByDescending(y => y.Date).FirstOrDefault().Salary ?? 0)
});

To elaborate, the TotalPay part of the query finds the salary (or logically speaking, their hourly pay) with the date closest to the left of the hours date, multiply it with the hours entry and add it to the final sum. If such an entry happens to not exist, then the query should return the 0, which i tried doing with the ?? 0 part, but my visual studio still ends up throwing an error without actually doing any calculating.


Solution

  • I'm guessing a little bit here, but I would try:

    time.GroupBy(x => x.User).Select(z => new
    {
       User = string.Format("{0} {1}", z.Key.Users.Name, z.Key.Users.Surname),
       Hours = z.Sum(x => x.Hours),
       TotalPay = z.Sum(x => x.Hours * 
            salaries
              .Where(y => y.User.Id == x.User.Id && y.Date <= x.Date)
              .OrderByDescending(y => y.Date)
              .Select(y => (double?)y.Salary)
              .FirstOrDefault() ?? 0)
    });