2

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

Heisenberg
  • 764
  • 6
  • 20
  • This answer to one of the questions you linked may help: https://stackoverflow.com/a/43537187/2169762 – Martin Dec 21 '18 at 20:26
  • Also this one, which is an extension method to do exactly what you are looking for: https://stackoverflow.com/a/43537671/2169762. Perhaps you should have looked thoroughly through the questions you linked in your own question. – Martin Dec 21 '18 at 20:27
  • Possible duplicate of [Force linq sum to return null](https://stackoverflow.com/questions/43537079/force-linq-sum-to-return-null) – Martin Dec 21 '18 at 20:27
  • How do I use TrueForAll in my group by code? I tried it with no success.it says IGrouping does not contain a definition of TrueForAll... – Heisenberg Dec 21 '18 at 20:28
  • @MartinParkin I have tried to make this extension to work, wrote this NullableSum but in the group by, I put JOB1= g.NullableSum(gs => gs.JOB1)....it was just throw errors : No overload for method NullableSum to take 1 arguement....can you give an example of code please? – Heisenberg Dec 21 '18 at 20:31

1 Answers1

1

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        
Yehor Androsov
  • 4,885
  • 2
  • 23
  • 40