开发者

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

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 >= 20开发者_开发百科10)
        .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.


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.


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})
                   );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜