Linq result if null then zero

c# entity-framework linq

Question

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.

1
4
5/27/2013 7:43:12 PM

Accepted Answer

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.

17
5/27/2013 7:14:06 PM

Popular Answer

You can just write:

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

The Enumerable.Sum method already returns zero on no results. From the documentation:

returns zero if source contains no elements.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow