Click here to Skip to main content
15,885,435 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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)
                      .DefaultIfEmpty(0)
                      .Sum().ToString());
      }
Posted
Updated 6-May-18 23:09pm

1 solution

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


[EDIT]
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:
C#
double?[] amounts = {null, null};
var result = amounts.Sum(); //returns 0 (zero)

or
C#
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!
 
Share this answer
 
v3
Comments
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    
What?
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();
//9.5

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

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900