In a LINQ to entities expression like this:
var vote = (from vote in db.Vote where
vote.Voter.Id == user.Id
select v).FirstOrDefault();
How do you add a DefaultIfEmpty value so that when there's no vote I'd get a default value?
in conclusion no, it won't return null since null can't say sequence contains no elements it will always say object reference not set to an instance of an object ;) Does this answer the question?
DefaultIfEmpty<TSource>(IEnumerable<TSource>) Returns the elements of the specified sequence or the type parameter's default value in a singleton collection if the sequence is empty.
The default value for reference and nullable types is null . The FirstOrDefault method does not provide a way to specify a default value.
The DefaultIfEmpty operator is used to replace an empty collection or sequence with a default valued singleton collection or sequence. Or in other words, it returns a collection or sequence with default values if the source is empty, otherwise return the source.
Another approach, if Vote
is a reference type and thus uses null as its default value, would be to use the null coalescing operator:
var vote = (db.Vote
.Where(v => v.Voter.Id == user.Id)
.FirstOrDefault()) ?? defaultVote;
Add your own extension method. For instance:
public static class Extension
{
public static T FirstOrDefault(this IEnumerable<T> sequence, T defaultValue)
{
return sequence.Any() ? sequence.First() : defaultValue;
}
}
With that class in scope, you can say:
var vote = (from vote in db.Vote where
vote.Voter.Id == user.Id
select v).FirstOrDefault(yourDefaultValue);
Of course, your method can also have an overload that returns default(T), if that was what you where looking for. There is already defined a DefaultIfEmpty extension method in the built-in Extension class, so I named the method in the example "FirstOrDefault", which seems like a better fit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With