Click here to Skip to main content
14,238,693 members
Rate this:
Please Sign up or sign in to vote.
See more:
string query = "select isnull(sum(amount),0) [amount] from Recharge.dbo.AirtimePromoTable";

i have a project full of raw query string and connection string and now i was task to create entity framework for the project.
How do i check for ISNUll and sum using LINQ to SQL

What I have tried:

Here is what i have tried but its not working...

using (var Context = new RechargeEntities())
        var Que = (from b in Context.AirtimePromoTables
                      .Select(b => b.Amount)
Updated 6-May-18 23:09pm

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

This should work:
using (var Context = new RechargeEntities())
        var Que = Context.AirtimePromoTables
                      .Sum(b => b.Amount);

You don't need to check whetever amount is null or not. You don't even need to convert nulls to zeros to be able to sum it up, because Enumerable.Sum Method (IEnumerable(Nullable(Double))) (System.Linq)[^] accepts nullable values as an input parameter.
So, using:
.Sum(b => b.Amount!=null ? b.Amount : 0);

is redundant!

Check this:
double?[] amounts = {null, null};
var result = amounts.Sum(); //returns 0 (zero)

double?[] amounts1 = {null, 2.5, 1.5, 0.5, 0.25, 1.75, 3.0, null};
var result1 = amounts.Sum(); //returns 9.5

Good luck!
wizklaus 7-May-18 6:12am
Thanks Maciej for your reply... But it doesn't check if the value ISNULL
Maciej Los 7-May-18 6:28am
Sum method accepts nullable value as parameter. So, you don't need to convert null into zero...
Check this:
double?[] amounts = {null, 2.5, 1.5, 0.5, 0.25, 1.75, 3.0, null};
var result = amounts.Sum();

In case of nulls only, sum will return zero!
Karthik_Mahalingam 7-May-18 7:13am
Maciej Los 7-May-18 7:51am
Thank you, Karthik.
Wendelius 7-May-18 11:24am
Nise, a 5.
Maciej Los 7-May-18 13:43pm
Thank you, Mika.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100