Using only the year part of a date for a WHERE condition

ε祈祈猫儿з 提交于 2021-01-26 20:34:41

问题


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

EDIT #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)

Why is .Value necessary to access .Year? Exam is a nullable datetime.


回答1:


You can just use the Year property on DateTime:

var active = from p in dc.People
             where p.Exam.Year >= 2010
             select new {
                 p.ContactID,
                 p.FirstName,
                 p.LastName
             };

Why is .Value necessary to access .Year? Exam is a nullable datetime.

Exactly because Exam is a Nullable<DateTime>. When you declare an instance of Nullable<DateTime> like

DateTime? exam;

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;

is a DateTime assuming that exam is not null. You can therefore say

int year = instance.Year;

and, of course, for brevity

int year = exam.Value.Year;

Note that this will throw if exam.HasValue is false.




回答2:


I don't know the most elegant way but this is the simplest way you can do it assuming examdate is the datetime col which you store your date and based on I want to select people with an exam date in 2010-

var active = dc.People.Where(x => x.examdate.year == 2010)
        .Select(x => new {x.ContactID, x.FirstName, x.LastName})
                   );


来源:https://stackoverflow.com/questions/4694352/using-only-the-year-part-of-a-date-for-a-where-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!