Search code examples
c#asp.netquery-expressions

compare age with birthdate in where clause


how to compare age with birthdate in where clause? Somthing like this code:

myRepository.Where(x =>
    fromAge <= x.BirthDate.Age && x.BirthDate.Age <= toAge)
    .Select(x).toList();

Data Types:

fromAge, toAge : int

x.BirthDate: DateTime


Solution

  • after searching, i ended up with this solution:

    toDate = DateTime.Now.AddYears(-fromAge).Date.AddYears(1).AddDays(-1);
    fromDate = DateTime.Now.AddYears(-toAge).Date.AddYears(-1).AddDays(+1);
    

    consider changing "fromAge" to "toDate" and "toAge" to "fromDate". so:

    myRepository.Where(x => fromDate <= x.BirthDate && x.BirthDate <= toDate)
        .Select(x).toList();