.net 如何比较 LINQ 中的日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/214426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to compare dates in LINQ?
提问by TedH
I want to check if a given date is more than a month earlier than today's date using LINQ.
我想使用 LINQ 检查给定日期是否比今天的日期早一个多月。
What is the syntax for this?
这是什么语法?
Thanks in advance.
提前致谢。
回答by tvanfosson
I assume that you're talking about in the where clause. It's basically the same way you would compare two DateTime objects elsewhere.
我假设你在 where 子句中谈论。这与比较其他地方的两个 DateTime 对象的方式基本相同。
using (DataContext context = new DataContext()) {
var query = from t in context.table
where t.CreateDate.Date < DateTime.Today.AddMonths(-1)
select t;
}
回答by live-love
Just to add, in LINQ To Entities you have to compare to a variable. Example:
只是补充一点,在 LINQ To Entities 中,您必须与变量进行比较。例子:
DateTime lastMonth = DateTime.Today.AddMonths(-1);
using (var db = new MyEntities())
{
var query = from s in db.ViewOrTable
orderby s.ColName
where (s.StartDate > lastMonth)
select s;
_dsResults = query.ToList();
}
回答by Pallavi
If you don't want your code to throw
如果你不想你的代码抛出
LINQ to Entities does not recognize the method 'System.DateTime AddYears(Int32)' method, and this method cannot be translated into a store expression.
I would suggest using DbFunctions.AddYears. Also, if you are concerned only about dates and not the times, you could use DbFunctions.TruncateTime
我建议使用 DbFunctions.AddYears。此外,如果您只关心日期而不是时间,则可以使用 DbFunctions.TruncateTime
Something like this-
像这样的东西——
DbFunctions.TruncateTime(x.date) ==
DbFunctions.TruncateTime(DbFunctions.AddYears(DateTime.Today, 1))

