2014-04-21 143 views
2

我想知道什麼是通過與這些格式的集合搜索的最佳方式:年齡最佳算法?

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

我的生日,IE瀏覽器1943年10月10日,現在讓我們假設我有一個接受兩個參數的方法像這樣:

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

問題是如何在Person集合上進行搜索以獲取年齡介於MAX和MIN之間的人作爲參數傳遞?

我正在陷入困境!

在此先感謝。

+0

除非你的收集是由生日排序的,你只需要'通過它foreach'和檢查每個人。 – Blorgbeard

+0

那麼,LINQ在C#中有'orderby' ... –

+0

這是LINQ到對象,還是連接到數據庫? –

回答

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

+1無需將每個dob轉換爲年齡......只需將年齡範圍轉換爲日期範圍即可。 – dotjoe

+0

@dotjoe謝謝老兄! – Christos

+0

完美無瑕。像迷人的一樣工作。 – MRFerocius

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; 
+0

是的,它可能是一個好主意,使其成爲'人'類的一部分。不過,我真的希望你的意思是*只讀屬性*,而不是*抽象* :) – MarcinJuraszek

+0

啊是的,只讀不是抽象的。我感到困惑。在我看來,'abstract'的含義與C#中的不同。 – mason

+0

對於GetAge的定製邏輯+1,因爲有時需要知道「上次檢查時患者的年齡」,而DateTimeNow在這種情況下沒有任何意義 – xmojmr

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