views:

52

answers:

3

Hi I have a table with many anniversaries : Date + Name.

I want to display the next anniversary and the one after with Linq.

How can i build the query ? I use EF Thanks John

+1  A: 

Just order by date and then use the .Take(n) functionality

Fredou
+1  A: 

Example with a list of some objects assuming you want to order by Date then Name:

List<Anniversaries> annivDates = GetAnnivDates();
List<Anniversaries> recentAnniv = annivDates.OrderBy(d => d.Date).ThenBy(d => d.Name).Take(2).ToList();
Kelsey
A: 

If the anniversaries are stored in regular DateTime structs, they may have the 'wrong' year set (i.e. wedding or birth year). I suggest writing a function which calculates the next date for an anniversary (based on the current day) like:

static DateTime CalcNext(DateTime anniversary) {
  DateTime newDate = new DateTime(DateTime.Now.Year, anniversary.Month, anniversary.Day);
  if (newDate < DateTime.Now.Date)
    newDate = newDate.AddYear(1);
  return newDate;
}

Then you proceed with sorting the dates and taking the first two values like described in the other postings:

(from e in anniversaries orderby CalcNext(e.Date) select e).Take(2)
MartinStettner