I am trying to check for people in a certain range – let lb-lowerbound and ub-upper bound corresponding for e.g. age group with lb=18 and ub=24 meaning I am trying to filter out the people aged between 18 and 24.Also Datetime field in database for date of birth is nullable.I have this code –
var users=from e in employee
where e.DOB.HasValue && ((DateTime.Now.Year - e.DOB.Value.Year)) >= lb)
&& ((DateTime.Now.Year - e.DOB.Value.Year) <= ub)
select e;
but this is only checks with the year how do I use the month and find out the actual age and filter out the users according to their age ? Thanks everyone for their help.
Firstly, that query is incorrect in terms of times during the year – you could be 17 and still counted as 18, for example – very few people born in 1993 are 18 as of today (January 17th 2011). Also, it’s computing
DateTime.Nowmultiple times, which means the year could vary while the query is executing.Finally, if you’ve just got a single
whereclause and yourselectclause is a no-op, it’s generally simpler to use the extension method syntax rather than a query expression.I would suggest:
EDIT: To be clearer, for a maximum age of (say) 10, that means you want to exclude anyone whose date of birth was 11 years ago or more, so you’d write: