var result = foo.FirstOrDefault(f => f.bar == barVal).someProperty
This will not work if there is no match (default is null) - trying to access a property on a null object. We can rewrite as follows:
var result = foo.Where(f => f.bar == barVal)
.Select(f => f.someProperty).DefaultIfEmpty(0).First()
Whilst it works, this doesn't seem like the most elegant way to do this... is there a better way?
Of course one can do something such as:
var result = 0;
var tmp = foo.FirstOrDefault(f => f.bar == barVal);
if(tmp != null) result = tmp.someProperty
But in a more complex query this approach looks to be even 'messier' than the DefaultIfEmpty approach
var tmpSet = dataSet.GroupBy(f => f.ID);
var newSet = tmp.Select(f => new {
ID = f.ID,
SomeProperty = f.Where(g => g.bar == barVal)
.Select(f => f.SomeProperty)
.DefaultIfEmpty(0).First()
});