问题描述
在下面的LINQ语句中,我想选择一个具有2010年考试日期的人.考试日期存储为日期时间,因为其他应用程序中使用了实际日期和时间.将exzam日期与仅'2010'进行比较的最优雅,最简单,最佳方法是什么.或者,我应该使用> =比较考试日期与2010年1月1日吗?
In the LINQ statement below, I want to select people with an exam date in 2010. The exam date is stored as a datetime as the actual date and time is used in other applications. What is the most elegant, easiest, best way to compare the exzam date to only '2010'. Or, should I just compare, using >=, the exam date to 1/1/2010?
var active = dc.People.Where(x => x.exam >= 2010)
.Select(x => new {x.ContactID, x.FirstName, x.LastName})
);
x.MostRecent == DateTime.Parse("1/1/2010").Year
编辑#1
我以为我应该在考试日期看到一个年份,但是没有.在这里看到几篇文章后,我回过头去发现了这项工作...
I thought I should see a .Year on the exam date but I didn't. After seeing a couple of posts here I went back and found this works...
.Where(x => x.exam.Value.Year == 2010)
为什么需要使用.Value来访问.Year?考试是可以为空的日期时间.
Why is .Value necessary to access .Year? Exam is a nullable datetime.
推荐答案
您可以在 DateTime
上使用 Year
属性:
var active = from p in dc.People
where p.Exam.Year >= 2010
select new {
p.ContactID,
p.FirstName,
p.LastName
};
正是因为 Exam
是 Nullable< DateTime>
.当您声明类似
Nullable< DateTime> 的实例时
Exactly because Exam
is a Nullable<DateTime>
. When you declare an instance of Nullable<DateTime>
like
DateTime? exam;
请注意,考试
不是 DateTime
,因此您不能直接访问 DateTime
的属性.要获取 DateTime
的具体实例,请在 Nullable< DateTime>
(所有 Nullable< T>
> s具有此属性)
note that exam
is not a DateTime
and therefore you can't directly access the properties of DateTime
. To get a concrete instance of DateTime
you use the Value
property on Nullable<DateTime>
(all Nullable<T>
s have this property) so that
DateTime instance = exam.Value;
是 DateTime
,假定 exam
不是 null
.因此,您可以说
is a DateTime
assuming that exam
is not null
. You can therefore say
int year = instance.Year;
当然是为了简洁
int year = exam.Value.Year;
请注意,如果 exam.HasValue
为false,则会抛出此错误.
Note that this will throw if exam.HasValue
is false.
这篇关于仅将日期的年份部分用于WHERE条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!