使用 Linq 或 Lambda 表达式的 SQL 之间的等效语句 [英] Equivalent of SQL Between Statement Using Linq or a Lambda expression
问题描述
不要认为这是转帖,很难搜索之间的词,因为它用于所有事物(例如搜索AND).
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.
我有一个包含一些日期的列表,我想按日期范围过滤它们.SQL 中是否有与 between
语句等效的 Linq 或 Lambda.
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.
例如,下面的代码在 Linqpad(或 Visual Studio)中不起作用:
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;}
}
推荐答案
类似的事情?
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));
我看到您提供了一些将日期作为字符串的示例.如果可能的话,我绝对会将解析逻辑(DateTime.ParseExact
或其他)与查询分开.
I see you've provided some samples with the dates as strings. I would definitely keep the parsing logic (DateTime.ParseExact
or other) separate from the query, if at all possible.
这篇关于使用 Linq 或 Lambda 表达式的 SQL 之间的等效语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!