Search code examples
c#linqsumnullable

Linq GROUP BY and SUM nullable long


Here is my code:

var Summary = ccL3.GroupBy(g => new
            {                    
                g.JOB_BASE_NUM,
                g.TOP_CUSTOMER_ID,
                g.TOP_DESCRIPTION

            })
               .Select(g => new Type2
               {                       
                   JOB_BASE_NUM = g.Key.JOB_BASE_NUM,
                   TOP_CUSTOMER_ID = g.Key.TOP_CUSTOMER_ID,
                   TOP_DESCRIPTION = g.Key.TOP_DESCRIPTION,
                   SUM_JOB1 = g.Sum(gs => gs.JOB1)                       
               })

EDIT: This is not a duplicate. The previous discussion cannot be directly used in GROUP BY.

JOB1 is nullable long.

The problem is that I need the SUM_JOB1 to be null if all JOB1 in ccL3 is null (It returns 0 if all is null or if the sum is 0).

I searched the following topics, but there is no discussion of SUM of null in GROUP BY in linq. Can someone help me please. Thank you.

Reference: handle null in linq sum

Linq query with nullable sum

Force linq sum to return null


Solution

  • If any item is not null, then use Sum, otherwise null

    SUM_JOB1 = g.Any(gs => gs.JOB1 != null) ? g.Sum(gs => gs.JOB1) : null