Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Unable To Cast Issue

Tags:

c#

casting

linq

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.

like image 896
bd528 Avatar asked Jan 22 '13 21:01

bd528


Video Answer


2 Answers

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.

like image 108
Maarten Avatar answered Oct 25 '22 02:10

Maarten


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..."

like image 31
Chris A Avatar answered Oct 25 '22 03:10

Chris A