适合年龄的最佳算法?

时间:2014-04-21 19:57:15

标签: c# algorithm linq

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

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

我有生日,I.E 10/10/1943,现在假设我有一个方法,它有两个这样的参数:

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

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

我被困了!

提前致谢。

3 个答案:

答案 0 :(得分: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);
}

我认为Persons是你所有人的集合。

答案 1 :(得分:6)

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

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;

答案 2 :(得分:2)

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