Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you return a default value if a LINQ to entities query returns no values

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?

like image 284
pupeno Avatar asked Jul 14 '09 18:07

pupeno


People also ask

Does Linq ever return null?

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?

What does DefaultIfEmpty return in Linq?

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.

What is default value Linq?

The default value for reference and nullable types is null . The FirstOrDefault method does not provide a way to specify a default value.

When should I use DefaultIfEmpty?

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.


2 Answers

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;
like image 167
Robert Rossney Avatar answered Oct 19 '22 18:10

Robert Rossney


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.

like image 30
driis Avatar answered Oct 19 '22 16:10

driis