DateTime List find last date that before current

I have a list of dates:

var dates = new List<DateTime>
        {
            new DateTime(2016, 01, 01),
            new DateTime(2016, 02, 01),
            new DateTime(2016, 03, 01),
            new DateTime(2016, 04, 01),
            new DateTime(2016, 05, 01)
        };

Now given a certain date, a "StartDate". What is the easiest way to create a list of dates after the startdate, and the last date before?

I.E. - If I supply the date DateTime(2016, 03, 15), I need to return

DateTime(2016, 03, 01),
DateTime(2016, 04, 01),
DateTime(2016, 05, 01)

It could be as simple as finding the last "Active" date and then just using the where from that date. But I'm unsure on how to do this without making it really complicated.

Jon Skeet
people
quotationmark

If your list is already sorted, you can use a binary search:

var index = dates.BinarySearch(start);
// If the precise value isn't found, index will be the bitwise complement
// of the first index *later* than the target, so we need to subtract 1.
// But if there were no values earlier, we should start from 0.
if (index < 0)
{
    index = Math.Max(~index - 1, 0);
}
return dates.Skip(index).ToList();

This assumes the dates are unique. If there are multiple dates the same as start, there's no guarantee that it will find the first one. If that's a concern, you'd need to search backwards until you found the first match.

You haven't specified whether if there's an exact match, you want to include the date before that or not. If you do, you'll need to adjust this code a bit.

people

See more on this question at Stackoverflow