最佳年龄算法

本文关键字:算法 最佳 | 更新日期: 2023-09-27 17:59:10

我想知道用以下格式搜索集合的最佳方式是什么:

public class Person
{
   public  DateTime Birthdate {get; set;}
}

我有出生日期,1943年10月10日,现在让我们假设我有一个方法,需要两个参数,如下所示:

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

问题是如何在Person集合中搜索,以获取年龄在MAX和MIN整数之间的人作为参数传递?

我被卡住了!

提前谢谢。

最佳年龄算法

试试这个:

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);
}

我想Persons是你所有人的集合。

首先,您必须了解如何使用生日和当前日期计算年龄。

public static int GetAge(DateTime birthDate)
{
    // your age logic goes here
}

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

return from p in people
       let age = GetAge(p.Birthdate)
       where age >= AgeMin && age <= AgeMax
       select p;
public IEnumerable<Person> SearchByAgeRange(this IEnumerable<Person> personCollection, int AgeMin, int AgeMax)
{
    return personCollection.Where(c=> {
        var currentAge =(((DateTime.Now - c.Birthdate).TotalDays+1) / 365.25);
        return currentAge > AgeMin && currentAge<AgeMax;
    });
}