Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
765 views
in Technique[技术] by (71.8m points)

c# 4.0 - Equivalent of SQL Between Statement Using Linq or a Lambda expression

Don't think this is a repost, difficult to search for the word between because it is used in everything (like searching for AND).

I want to filter a list based on a date range.

I have a list with some dates and I want to filter them by a date range. Is there a Linq or Lambda equivalent of the between statement in SQL.

For example, the code below will not work in Linqpad (or Visual Studio):

void Main()
{
    List<ListExample> list = new List<ListExample>();

    list.Add(new ListExample("Name1","23 Aug 2010"));
    list.Add(new ListExample("Name2","23 Aug 2009"));

    var query = from l in list
        where l.DateValue between "01 Jan 2010" and "01 Jan 2011"
        select l;

}

public class ListExample
{

    public ListExample(string name, string dateValue)
    {
        Name = name;
        DateValue = DateTime.Parse(dateValue);
    }

    public string Name{get;set;}
    public DateTime DateValue{get;set;}
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Something like this?

var query = from l in list
            where l.DateValue >= new DateTime(2010, 1, 1) 
               && l.DateValue <= new DateTime(2011, 1, 1)
            select l;

You can write your own extension method:

public static bool IsBetween(this DateTime dt, DateTime start, DateTime end)
{
   return dt >= start && dt <= end;    
}

In which case the query would look something like (method syntax for a change):

var start = new DateTime(2010, 1, 1);
var end = new DateTime(2011, 1, 1);
var query = list.Where(l => l.DateValue.IsBetween(start, end));

I see you've provided some samples with the dates as strings. I would definitely keep the parsing logic (DateTime.ParseExactor other) separate from the query, if at all possible.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...