Linq can't challenge

When i try to run

InvTotal = g.Sum(d => d.Field<double>("Total")) < 0 ? "W" : "N", I get

Unable to cast object of type 'System.Double' to type 'System.String' error.

How do I change the code to compile it successfully.

+5
source share
3 answers

I think you need the right bracket.

var InvTotal = (g.Sum(d => d.Field<double>("Total")) < 0) ? "W" : "N"

Without them, the compiler will compile first 0 ? "W" : "N", and the result of this will be used in comparison.

Sometimes the C # compiler needs a little help if it comes to? Operator.

+10
source

What is the type of InvTotal? I guess this is Double now. This should work if you change the type to String or delete the InvTotal declaration and change your string to "var InvTotal = g.Sum ..."

+1
source

, .

InvTotal, var InvTotal =...., .

:

# - :

int x = 2;
var tmp = x ? "W" : "N";

, :

: " " int "" bool ""

# ++, false, true.

So you can write something like this:

g.Sum(d => d.Field<double>("Total")) < 0 ? "W" : "N"

you can also have several logical operators without parentheses in the first section of the triple operator:

g.Sum(d => d.Field<double>("Total")) < 0 && 1 == 1 && 2 != 4 && 9 != 0 ? "W" : "N";
0
source

All Articles