Home > Software engineering >  Find most recent time from list compared to my current time C#
Find most recent time from list compared to my current time C#

Time:12-09

I have a list of times:

1:00
3:00
5:00

I need to select the most recent one compared to my current time.

So say the current time is 2:50, I need the code to select 1:00. If the current time was 3:30, it would select 3:00, etc.

How can I write a for loop to accomplish this with any given list of times and a current time?

CodePudding user response:

You can query times with a help of Linq MinBy, e.g. having

        TimeOnly[] times = {
            new TimeOnly(1, 0),
            new TimeOnly(3, 0),
            new TimeOnly(5, 0),
        };

and

        TimeOnly current = new TimeOnly(2, 50);

you can put

        using System.Linq;

        ...

        var mostRecent = times
            .Where(time => time <= current) // past time only
            .MinBy(time => current - time);

No Linq solution can be a for loop:

        TimeOnly mostRecent = TimeOnly.MinValue;

        foreach (TimeOnly time in times)
            if (time <= current && mostRecent < time)
                mostRecent = time;

Edit: If collection (TimeOnly[] times) is in fact ordered we can use binary search instead of scan (see Eric J. comment):

        // if times is List<> then the syntax should be
        // int index = times.BinarySearch(current);
        int index = Array.BinarySearch(times, current);

        TimeOnly mostRecent = index >= 0 ? times[index] : times[~index - 1];
  • Related