Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq expression for executing a "Between"

Tags:

c#

linq

between

In SQL you have the ability to write a query that executes a between on a column that is of type 'nvachar' and simply returns to you all the rows that are between the min and max values specified.

For Example,

Table (Id:Int, Name:nvarchar):

Contents:
1, Annie
2, Bill
3, Frank
4, Phil
5, Ted

Select * where Name Between 'Frank' and 'Ted'

Should return Frank, Phil, and Ted.

Is there a way to do this with linq or am I going to have to create a custom query and execute it? The only examples I have seen involve dates or integers which make it very easy (can use the comparison operators like <, > etc).

like image 467
The Sheek Geek Avatar asked Sep 27 '26 01:09

The Sheek Geek


1 Answers

You'd use CompareTo instead:

var query = from name in names
            where name.CompareTo("Frank") >= 0 &&
                  name.CompareTo("Ted") <= 0
            select name;

Use > and < to be exclusive (i.e. to exclude Frank and Ted).

Basically it's the same as using < and >, but with methods :)

like image 63
Jon Skeet Avatar answered Sep 29 '26 16:09

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!