How to select the latest dateTime of every week ? C#

I have to implement an algorithm who receive a list of DateTime and its recovers the latest DateTime of every week.

Example:

29/06/2016 -> Lastest date of the last week of the month
27/06/2016
24/06/2016 -> Lastest date of the before last week of the month
22/06/2016
21/06/2016
15/06/2016 -> Lastest of the third week
13/06/2016
...

Expected result

29/06/2016
24/06/2016
15/06/2016

I dont ask the code who done that but some directions or indication for resolve this problem.

Jon Skeet
people
quotationmark

Note: this answer assumes that you're interested in "natural" weeks, which don't really care about the year. For example, December 31st 2015 was a Thursday, and January 1st 2016 was a Friday - to my mind (and using the algorithm in this answer) those would count as being in the same week... the Monday before/on both days is the same, after all.

The simplest solution to this is probably to group by "start of week", then take the latest value within each group. Finding the start of the week is slightly awkward, and best done in a helper method:

var latestPerWeek = dates.GroupBy(StartOfWeek)
                         .Select(g => g.Max())
                         .ToList();

...

private static DateTime StartOfWeek(DateTime date)
{
    date = date.Date; // Just remove any time parts...
    // 0=Sunday, 1=Monday... 6=Saturday
    int sundayToSaturdayDayOfWeek = (int) date.DayOfWeek;
    // 0=Monday, 1=Tuesday... 6=Sunday
    int mondayToSundayDayOfWeek = ((sundayToSaturdayDayOfWeek - 1) + 7) % 7;
    return date.AddDays(-mondayToSundayDayOfWeek);
}

Note that the .NET "week of year" handling is tempting to use, but basically doesn't handle this scenario. In Noda Time 2.0 this will be a lot simpler, but that isn't available yet...

people

See more on this question at Stackoverflow