Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FirstOrDefault inline null checking

I have following code :

var result = new Collection<object>();

result.Add(
     list.Select(s => new
     {
          s.Name,
          Rating = s.Performance.OrderByDescending(o => o.Year).FirstOrDefault().Rating
     })
);

If there's no record found in Performance, it will give me NullException which is expected because I'm trying to get Rating property from null value so my question is how to set null if FirstOrDefault() is null and get Rating value if not.

Thanks

like image 541
warheat1990 Avatar asked Mar 21 '26 07:03

warheat1990


1 Answers

Do this:

Rating = s.Performance.OrderByDescending(o => o.Year)
                      .Select(o => o.Rating)
                      .FirstOrDefault()
like image 73
Rob Avatar answered Mar 23 '26 21:03

Rob