在下面的 LINQ 语句中,我想选择考试日期为 2010 年的人员。考试日期存储为日期时间,因为其他应用程序中使用实际日期和时间。将考试日期与“2010”进行比较的最优雅、最简单、最好的方法是什么?或者,我应该使用 >= 将考试日期与 2010 年 1 月 1 日进行比较吗?
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
EDIT #1
我以为我应该在考试日期看到 .Year,但我没有。在这里看到几篇文章后,我回去发现这个有效......
.Where(x => x.exam.Value.Year == 2010)
为什么访问 .Year 需要 .Value? Exam 是一个可为空的日期时间。
你可以只使用Year
属性于DateTime
:
var active = from p in dc.People
where p.Exam.Year >= 2010
select new {
p.ContactID,
p.FirstName,
p.LastName
};
为什么访问 .Year 需要 .Value? Exam 是一个可为空的日期时间。
正是因为Exam
is a Nullable<DateTime>
。当你声明一个实例时Nullable<DateTime>
like
DateTime? exam;
注意exam
不是一个DateTime
因此你不能直接访问的属性DateTime
。获取具体实例DateTime
你使用Value
属性于Nullable<DateTime>
(all Nullable<T>
s 有这个属性)所以
DateTime instance = exam.Value;
is a DateTime
假如说exam
is not null
。因此你可以说
int year = instance.Year;
当然,为了简洁起见
int year = exam.Value.Year;
请注意,如果exam.HasValue
是假的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)