Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Convert.ToDouble(value) in Lambda LINQ Statement

Tags:

c#

linq

I have the following LINQ statement:

Items = Items.Where(p => p.LeadDatas.Any(
                         q =>
                         q.LeadField.Name == descriptor.Name &&
                         Convert.ToDouble(q.Value) == Convert.ToDouble(value)));

The q.Value is a String value of a double, and value is also a String value of a double, both of these needed to be converted to doubles so that they can be compared for equality.

When I debug over this LINQ statement, I am getting the following SQLException:

Error Converting data type varchar to float

I am not sure why it is not allowing me to do this, but I am wondering what the fix is, I need my two values to be compared for equality here.

like image 228
TheJediCowboy Avatar asked Aug 30 '11 15:08

TheJediCowboy


1 Answers

To start with, I would extract the Convert.ToDouble(value) out to a local variable:

double target = Convert.ToDouble(value);
Items = Items.Where(p => p.LeadDatas.Any(q =>
                             q.LeadField.Name == descriptor.Name &&
                             Convert.ToDouble(q.Value) == target));

It's quite possible that it's the attempted conversion of value that's the problem, rather than the attempted conversion of q.Value for some row. Alternatively, it could be that you've got a row which doesn't have a valid value. (You could try using double.TryParse but I'm not sure how well that's giong to work...)

However, it's also generally a bad idea to compare binary floating point values with simple equality in the first place. You may want to use some degree of tolerance (and exactly how that works with LINQ to SQL is another matter...)

like image 72
Jon Skeet Avatar answered Sep 18 '22 23:09

Jon Skeet