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
Do this:
Rating = s.Performance.OrderByDescending(o => o.Year)
.Select(o => o.Rating)
.FirstOrDefault()
You can use Enumerable.DefaultIfEmpty Method
Rating = s.Performance.OrderByDescending(o => o.Year)
.Select(o => o.Rating)
.DefaultIfEmpty(0)
.First()