jchitel
jchitel

Reputation: 3169

How to select a list of the latest times per day from a list of dates

That question probably sounded extremely confusing, but it's difficult to describe what I want to do. Basically, I have a list of DateTime objects and I want to make a new list that contains the objects from the list that represent the latest time for each date represented in the list. For example, say I have a list containing these DateTimes:

I want my results list to contain the following:

I know I can do this using LINQ. I'm just having a hard time trying to wrap my mind around what is happening. I think I have to select from an IEnumerable<IEnumerable<DateTime>> where the inner IEnumerable is a list of DateTimes that all have the same date, and then I want to order those by descending and select the first one.

I am quite lost...

Upvotes: 2

Views: 1262

Answers (2)

Stan R.
Stan R.

Reputation: 16065

You can do something like this

var groups = dateList.GroupBy(date => date.Date)
                     .Select( grp => grp.Max( date => date.TimeOfDay));

Upvotes: 1

eulerfx
eulerfx

Reputation: 37719

Try this:

var dates = list.GroupBy(dt => dt.Date).Select(g => g.Max());

Upvotes: 9

Related Questions