Question

I have a database with an amount field - it's a decimal, although the database schema has the column defined as a string. I want to be able to run a Linq query to find values based on a number for the amount.

There are questions like this and this that talk about using the CompareTo method, but that doesn't work in this situation. For example, I have the following bill amounts in the database:

556
130
1450
410

the following code:

from t in test
where t.BillAmount.CompareTo("50") > 0
select t

will return value 556 but not any of the other values, even though they are all above the decimal value of 50.

Changing the where line to:

    where t.BillAmount.CompareTo("50") < 0

will return 130, 1450, and 1450 as those are "less" then 50 as a string, but not as a number.

I'm not using the entity framework, so I can't do something like:

where SqlFunctions.StringConvert((double)t.BillAmount).Trim() > 50

I also don't have any control over the database schema, so I can't change these values. How can I compare the BillAmount field to a number and return the values above/below it?

Was it helpful?

Solution

You do not have to use Entity Framework to cast a String to Decimal.

You can simply use the Convert call.

var x = from t in test 
        where Convert.ToDecimal(t.BillAmount) > 50 
        select t

or with Lambda expression:

var x = test.where(p=>Convert.ToDecimal(p.BillAmount) > 50);

OTHER TIPS

This is a good place to use let, which will let you have a temporary variable as part of the LINQ query. Something like this should work:

from t in test
let amount = Convert.ToDecimal(t.BillAmount)
where amount > 50
select t
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top