2014-04-21 2 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

예,'Person' 클래스의 일부로 만드는 것이 좋습니다. 그러나, 나는 정말로 당신이 * readonly property *가 아니라, * abstract *가 아니길 희망했다. :) – MarcinJuraszek

+0

아, 읽기 전용으로 추상이 아니다. 나는 그 사람들을 혼란스럽게 만든다. 내 마음 속에서'추상적'은 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; 
    }); 
} 
관련 문제