Get current, future or most recent item

In the application I’m working on I had to repeatedly show information based on relevance by date. I wrote a little extension method to help select the current item, if there is no current item, then select the first future item, if there are no future items, then select the most recent item in the past.


public static class RelevantItemExtension
{
    public static T GetCurrentFutureOrMostRecent( this IEnumerable list,
                                                  Func<T, DateTime> dateSelector )
                                                  where T : class
    {
        if ( list.Count() == 0 )
        {
            return null;
        }
        else if ( list.Count() == 1 )
        {
            return list.First();
        }
        else
        {
            var currentOrFuture =
                list.Where( x => dateSelector( x ).Date >= DateTime.Today.Date )
                    .OrderBy( x => dateSelector( x ) )
                    .FirstOrDefault();

            if ( currentOrFuture != null )
            {
                return currentOrFuture;
            }
            else
            {
                return list.OrderBy( x => dateSelector( x ) )
                            .Last();
            }
        }
    }
}

I’m able to use this method as follows:

[TestMethod]
public void RelevantItemExtension_Future()
{
    // Arrange
    List list = new List() {
        new DataItem() { Value = 1, Date = DateTime.Today.AddDays(-21) },
        new DataItem() { Value = 2, Date = DateTime.Today.AddDays(-7) },
        new DataItem() { Value = 3, Date = DateTime.Today.AddDays(-14) },
        //new DataItem() { Value = 4, Date = DateTime.Today },
        new DataItem() { Value = 5, Date = DateTime.Today.AddDays(7) }
    };

    // Act
    var item = list.GetCurrentFutureOrMostRecent( x => x.Date );

    // Assert
    Assert.AreEqual( 5, item.Value );
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s