Linq expression for executing a “Between”

♀尐吖头ヾ 提交于 2019-12-10 21:36:19

问题


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


回答1:


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 :)



来源:https://stackoverflow.com/questions/7235859/linq-expression-for-executing-a-between

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!