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

pupeno picture pupeno · Jul 14, 2009 · Viewed 27.7k times · Source

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?

Answer

Robert Rossney picture Robert Rossney · Jul 14, 2009

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;