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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With