1

I have a LINQ statement which is working great... its part of select here it is

 select new
 {
     Net = (System.Double?)
     ((from m0 in MOVTOS
     where m0.DocumentType == "NET" && m0.ClientCode == c.ClientCode
     group m0 by new { 0.ClientCode } into g
     select new
     {
         Expr1 = (System.Double)g.Sum(p => p.Amount)
     }).First().Expr1)
};

Now if you notice i am using System.Double? (nullable double) as a cast at the begging due to the fact that some values are returned as NULL on the SUM.

If i change it to System.Double it fails with error

The null value cannot be assigned to a member with type System.Double which is a non-nullable value type

So what i would like to do is return the value of the SUM but if it is NULL then enter a 0 in there.

Any help really appreciated

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Martin
  • 23,844
  • 55
  • 201
  • 327

4 Answers4

5

Use the null coalescing operator:

double? nullable = null;
double notNullable = nullable ?? 0;

In your case:

select new
{
    Net =
        (from m0 in MOVTOS
         where m0.DocumentType == "NET" && m0.ClientCode == c.ClientCode
         group m0 by new { 0.ClientCode } into g
         select g.Sum(p => p.Amount) ?? 0).First()
};
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
1

Simply add ?? 0

Change .First().Expr1) to .First().Expr1) ?? 0

The Smallest
  • 5,713
  • 25
  • 38
0

Instead of Sum you can use the Aggregate method with a seed of 0.0. This does not require the use of nullable types, or explicit casting.

select new
{
    Net =
    ((from m0 in MOVTOS
    where m0.DocumentType == "NET" && m0.ClientCode == c.ClientCode
    group m0 by new { 0.ClientCode } into g
    select new
    {
        Expr1 = g.Aggregate(0.0, (a, p) => a + p.Amount)
    }).First().Expr1)
};
jackvsworld
  • 1,453
  • 15
  • 17
0

Or you can filter your collection g accordingly...

List<double?> dArr = new List<double?>( )
{
   1,
   3,
   null,
   5
};

double sum = dArr.Select( item =>
   {
       if( item.HasValue == false )
          return 0;
       else
          return item;
   } ).Sum( item => item.Value );
Viper
  • 2,216
  • 1
  • 21
  • 41