适合年龄的最佳算法?

MRF*_*ius 2 c# linq algorithm

我想知道用这些格式搜索集合的最佳方法是什么:

public class Person
{
   public  DateTime Birthdate {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

我有生日,IE 10/10/1943,现在让我们假设我有一个方法,它采用这样的两个参数:

public IEnumerable<Person> SearchByAgeRange(int AgeMin, int AgeMax)
{
    //Best algorithm goes here.
}
Run Code Online (Sandbox Code Playgroud)

问题是如何搜索Person集合以便将年龄介于MAX和MIN整数之间的人作为参数传递?

我被困了!

提前致谢.

Chr*_*tos 7

试试这个:

public IEnumerable<Person> SearchByAgeRange(int AgeMin, int AgeMax)
{
    // If the maximum age you are looking for is for instance 80, then you 
    // should look for dates that are greater or equal of the current datetime 
    // minus 80 years. This forms the minDate.
    DateTime minDate = DateTimeNow.AddYears(-AgeMax);

    // If the minimum age you are looking for is for instace 40, then you should 
    // look for dates that are less or equal of the current date minus 40 years.
    // This forms the maxDate.
    DateTime maxDate = DateTimeNow.AddYears(-AgeMin);

    return Persons.Where(x => x.Birthdate >= minDate && x.BirthDate <= maxDate);
}
Run Code Online (Sandbox Code Playgroud)

我想这Persons是你所有人的集合.


Mar*_*zek 6

首先,您必须弄清楚如何使用生日和当前日期计算年龄.

public static int GetAge(DateTime birthDate)
{
    // your age logic goes here
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用LINQ过滤集合:

return from p in people
       let age = GetAge(p.Birthdate)
       where age >= AgeMin && age <= AgeMax
       select p;
Run Code Online (Sandbox Code Playgroud)