[ACCEPTED]-How do you return a default value if a LINQ to entities query returns no values-defaultifempty

Accepted answer
Score: 19

Another approach, if Vote is a reference type 2 and thus uses null as its default value, would 1 be to use the null coalescing operator:

var vote = (db.Vote
   .Where(v => v.Voter.Id == user.Id)
   .FirstOrDefault()) ?? defaultVote;
Score: 5

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 8 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 7 method can also have an overload that returns 6 default(T), if that was what you where looking 5 for. There is already defined a DefaultIfEmpty 4 extension method in the built-in Extension 3 class, so I named the method in the example 2 "FirstOrDefault", which seems like a better 1 fit.

Score: 4

Just add the default value before getting 4 the first element.

var vote = db.Vote
    .Where(v => v.Voter.Id == user.Id)

Note that you can now 3 safely use First() instead of FirstOrDefault().


LINQ to Entity does 2 not recognize the DefaultIfEmpty() extension method. But 1 you can just use the null coalescing operator.

var vote = db.Vote.FirstOrDefault(v => v.Voter.Id == user.Id) ?? defaultVote;
Score: 1

I ended up going for a very simple approach 2 which was recommended by an answer here 1 that was latter erased:

var vote = (from vote in db.Vote 
            where vote.Voter.Id == user.Id
            select v).FirstOrDefault();
if (vote == null) {
    vote = new Vote() { .... };
Score: 0

For some reason if I turn the resultset 3 into a List, the Defaultifempty() works 2 I don't know if I've inadvertantly crossed 1 over into Linq area.

var results = (from u in rv.tbl_user
                        where u.tbl_province.idtbl_Province == prov
                       select new { u.firstName, u.cellNumber, u.tbl_area.Area, u.ID, u.tbl_province.Province_desc,
                                    pic = (from p3 in u.tbl_pics
                                           where p3.tbl_user.ID == u.ID
                                           select p3.pic_path).DefaultIfEmpty("defaultpic.jpg").First()

More Related questions