LINQ Datatable return 0 instead of null union

I have the following LINQ statement that computes 3 values ​​from a data table. Sometimes some of these values ​​may contain zero. How to make the equivalent of combining zero into 0.

var striko2scrap = from myrow in Scrap.AsEnumerable()
                   where myrow.Field<string>("MachineID") == "Striko 2"
                   group myrow by myrow.Field<string>("MachineID") == "Striko 2" into g
                   select new
                   {
                        TotalScrap = g.Sum(x => x.Field<int?>("Runners") ?? 
                                         0 + x.Field<int?>("HouseIngots") ?? 
                                         0 + x.Field<int?>("Other") ?? 
                                         0)
                   } ;

I tried?? 0 in different places, but when I debug, I still get the same result. enter image description here

+4
source share
4 answers

The problem you are facing is operator priority. I think you want to treat a nullas 0. This will:

int? a = null;
int? b = 1;
int? c = 2;

int result = (a ?? 0) + (b ?? 0) + (c ?? 0); // 3

What you wrote is equivalent

int result = a ?? (0 + b) ?? (0 + c) ?? 0; // 1

So, all you have to do is change g.Sum(x => ...), and it should work as intended.

+5
source

HasValue Value , :

select new
{
    TotalScrap = g.Sum(x => 
      (x.Field<int?>("Runners").HasValue ? x.Field<int?>("Runners").Value : 0 ) +
      (x.Field<int?>("HouseIngots").HasValue ? x.Field<int?>("HouseIngots").Value : 0 ) +
      (x.Field<int?>("Other").HasValue ? x.Field<int?>("Other").Value : 0 )
)};

??, :

select new
{
    TotalScrap = g.Sum(x => 
      (x.Field<int?>("Runners") ?? 0 ) +
      (x.Field<int?>("HouseIngots") ?? 0 ) +
      (x.Field<int?>("Other") ?? 0 )
)};
+1

:

var striko2scrap = from myrow in Scrap.AsEnumerable()
                   where myrow.Field<string>("MachineID") == "Striko 2"
                   group myrow by myrow.Field<string>("MachineID") == "Striko 2" into g
                   select new
                   {
                        TotalScrap = g.Sum(x => 
                            (x.Field<int?>("Runners") ?? 0) +
                            (x.Field<int?>("HouseIngots") ?? 0) +
                            (x.Field<int?>("Other") ?? 0))
                   } ;
0

You tried

x.Field<int?>("Runners").Value ?? 0

or

x.Field<int?>("Runners").HasValue ? x.Field<int?>("Runners") : 0
0
source

Source: https://habr.com/ru/post/1525785/


All Articles