Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to SQL value BETWEEN two double values

I'm using LINQ to SQL to query my database, I have a query very similar to this:

var result = from db.MyTable.Where(d => (double)d.Price >= minValue)

I need the where clause to have a d.Proce >= minValue, and d.Price =< maxValue (like a T-SQL BETWEEN clause).

How can I do this?

like image 275
Alex Avatar asked Sep 12 '09 11:09

Alex


2 Answers

How about this:

var result = from db.MyTable.Where(d => (double)d.Price >= minValue 
                                         && (double)d.Price <= maxValue)
like image 111
cjk Avatar answered Oct 07 '22 13:10

cjk


Just for completeness; if you are building a query based on different inputs you can compose it with successive Where calls:

IQueryable<SomeType> query = db.MyTable;
if(minValue != null) // a Nullable<double>
{
    var actualMin = minValue.Value;
    query = query.Where(d => (double) d.Price >= actualMin);
}
if(maxValue != null) // a Nullable<double>
{
    var actualMax = maxValue.Value;
    query = query.Where(d => (double) d.Price <= actualMax);
}
// keep working with "query", for example, query.ToList();
like image 35
Marc Gravell Avatar answered Oct 07 '22 12:10

Marc Gravell