Using only the annual part of the date for the WHERE clause

In the LINQ instruction below, I want to select people with an exam date in 2010. The exam date is stored as a date-time, since the actual date and time are used in other applications. What is the most elegant, easiest and best way to compare exzam date only with "2010". Or, if I just compare, using> =, the exam date is before 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 

CHANGE NO. 1

I thought I should see a year on the exam, but I did not. After seeing a couple of posts here, I came back and found that this works ...

 .Where(x => x.exam.Value.Year == 2010) 

Why do I need access. An exam is a date and time with a value of zero.

+8
linq entity-framework entity-framework-4
source share
2 answers

You can simply 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 do I need access. An exam is a date and time with a value of zero.

Precisely because Exam is a Nullable<DateTime> . When you declare an instance of Nullable<DateTime> as

 DateTime? exam; 

note that Exam not a DateTime , so you cannot directly access DateTime properties. To get a specific instance of DateTime , you use the Value property in Nullable<DateTime> (all Nullable<T> have this property) to

 DateTime instance = exam.Value; 

is a DateTime , assuming Exam not null . Therefore you can say

 int year = instance.Year; 

and of course for brevity

 int year = exam.Value.Year; 

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

+18
source share

I don’t know the most elegant way, but this is the easiest way to do this, considering that examdate is a datetime col in which you save the 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
source share

Source: https://habr.com/ru/post/651081/


All Articles