使用Linq或Lambda表达式的SQL之间的等效SQL语句 [英] Equivalent of SQL Between Statement Using Linq or a Lambda expression
问题描述
不要认为这是一个转贴,很难搜索之间的单词,因为它用于一切(如搜索AND)。
我想过滤基于日期范围的列表。
我有一个列表包含一些日期,我想通过日期范围过滤它们。是否有一个Linq或Lambda等效于 c>语句之间的语句。
例如,下面的代码不会工作在Linqpad(或Visual Studio):
void Main()
{
List< ListExample> list = new List< ListExample>();
list.Add(new ListExample(Name1,2010年8月23日));
list.Add(new ListExample(Name2,2009年8月23日));
var query = from l in list
其中l.DateValue介于2010年1月1日和2011年1月1日之间
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
其中l.DateValue> = new DateTime(2010,1,1)
&& l.DateValue< = new DateTime(2011,1,1)
select l;
您可以编写自己的扩展方法:
public static bool IsBetween(this DateTime dt,DateTime start,DateTime end)
{
return dt> = start&& dt <= end;
}
在这种情况下,查询将类似(更改的方法语法) :
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
或其他)与查询分离,如果可能的话。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;} }
解决方案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.ParseExact
or other) separate from the query, if at all possible.这篇关于使用Linq或Lambda表达式的SQL之间的等效SQL语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!