FirstOrDefault inline null checking

c# entity-framework entity-framework-6 linq

Question

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

1
3
8/25/2015 2:42:15 AM

Accepted Answer

Do this:

Rating = s.Performance.OrderByDescending(o => o.Year)
                      .Select(o => o.Rating)
                      .FirstOrDefault()
9
8/25/2015 2:50:46 AM

Popular Answer

You can use Enumerable.DefaultIfEmpty Method

Rating = s.Performance.OrderByDescending(o => o.Year)
                      .Select(o => o.Rating)
                      .DefaultIfEmpty(0)
                      .First()


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow