bd528
bd528

Reputation: 886

Linq Unable To Cast Issue

When I try to run

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

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

How do I need to change the code for it it compile successfully.

Upvotes: 5

Views: 267

Answers (3)

kmatyaszek
kmatyaszek

Reputation: 19296

I think that in this case it's no problem with parenthesis.

Problem is with type of InvTotal, if you write var InvTotal =.... everything will be ok.

Explanation to Maarten answer:

In C# we can not write something like that:

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

If we try, we will get following error:

Error: "Cannot implicitly convert type 'int' to 'bool'"

C# is not C++ where zero indicates false and nonzero values indicates true.

So you can write something like that:

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

you can also have multiple logic operators without parenthesis in first section of ternary operator:

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

Upvotes: 0

Maarten
Maarten

Reputation: 22945

I think you need correct parenthesis.

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

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

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

Upvotes: 10

Chris A
Chris A

Reputation: 190

what is the type of InvTotal? I'm guessing it is currently a Double. Should work if you change the type to String, or remove the declaration of InvTotal and change your line to "var InvTotal = g.Sum..."

Upvotes: 1

Related Questions