Equivalent of SQL Between Statement Using Linq or a Lambda expression

前端 未结 3 1566
南笙
南笙 2020-12-09 11:36

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

相关标签:
3条回答
  • Datetime DT1 = DateTime.Parse("01 Jan 2010");
    Datetime DT2 = DateTime.Parse("01 Jan 2011");
    var query = from l in list
                where l.DateValue >= DT1 && l.DateValue <= DT2
                select l;
    

    in linq you use the && and || like you would in a normal boolean statement of C#.

    0 讨论(0)
  • 2020-12-09 11:56
    var query = from l in list
            where new DateTime(1,1,2010) <= l.DateValue and DateValue <= new DateTime(1,1,2011)
            select l;
    

    of course, normally warning about timezones and different times on clients and servers apply

    0 讨论(0)
  • 2020-12-09 12:03

    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.

    0 讨论(0)
提交回复
热议问题