I am trying to check for people in a certain age range. I have two ComboBoxes, minagecombobox and maxagecombobox, with values between 1 and 120.
I want to get the people whose age is between these two values (suppose for example I want to filter out the people aged between 18 and 24).
This is the Member table structure:
member_id
member_firstname
member_dob(datatype is string)
And my entity name i开发者_运维知识库s dbcontext. I am using Entity Framework and LINQ to Entities.
Just calculate the age and compare it with your desired age interval. The age calculation isn't exactly the best, but it's good enough as an example:
DateTime now = DateTime.Now;
int min = 18, max = 20;
var res =
from m in Member
let Age = System.Data.Objects.SqlClient.SqlFunctions.DateDiff("y", t.member_dob, now)
where Age >= min && Age <= max
select m;
DoBConverted = (Today's date - age(in years)) // in datetime
would give you the date of birth.
Simiarly, parse DoB (string) to get datetime.
You can perform a check with dob value with min dob and max dob to get the records.
int minAge = 18, maxAge=20;
DateTime convertedMinDob = DateTime.Now.AddYears(-minAge);
DateTime convertedMaxDob = DateTime.Now.AddYears(-maxAge);
Console.WriteLine(convertedMinDob.ToString() + " " + convertedMaxDob.ToString());
string strDate = "1/1/1995";
DateTime actualDate = DateTime.Parse(strDate);
bool valid = actualDate >= convertedMaxDob && actualDate <= convertedMinDob;
Console.WriteLine(valid? "In range": "Out of range");
精彩评论