Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq result if null then zero

How do I write something like this:

            int result = database
                .Where(x => x.Name == "Criteria")
                .Sum(x => x.Count)) ?? 0;

Where it will return the sum value unless linq does not find anything in which case it will return 0.

EDIT: The field is not null-able.

EDIT 2: I am using Entity Framework.

like image 350
Bill Software Engineer Avatar asked Nov 28 '22 11:11

Bill Software Engineer


2 Answers

You were very close with your original query. You only needed to cast your Count variable:

int result = database
    .Where(x => x.Name == "Criteria")
    .Sum(x => (int?)x.Count) ?? 0;

Doing it this way would be a little more efficient and elegant than wrapping it in a Try/Catch.

I suspect you are using Entity Framework. If you were just using Linq-to-Objects, the solutions everybody else have provided would have worked.

like image 99
Brad Rem Avatar answered Dec 06 '22 00:12

Brad Rem


This should work fine (no need for ?? 0):

var result = database
.Where(x => x.Name == "Criteria")
.Sum(x => x.Count))

Unless you want to check if x itself is null or not:

var result = database
.Where(x => x != null)
.Where(x => x.Name == "Criteria")
.Sum(x => x.Count))
like image 40
Kaveh Shahbazian Avatar answered Dec 05 '22 23:12

Kaveh Shahbazian