Monthly Archives: September 2014

n-1

Given the nth item, grab the n-1 item in a list.

Simple, right? You essentially create a stack of size 1 to hold the previous element.

public T GetPrevious<T>(IOrderedEnumerable<T> list, T target)
{
    var previous = null;

    foreach (var item in list)
    {
        if (item == target)
        {
            break;
        }

        previous = item;
    }

    return previous;
}

As usual, LINQ provides a more condensed and elegant solution:

public T GetPrevious<T>(IEnumerable<T> list, T target)
{
    return list
        .OrderByDescending(i => i.Updated)
        .SkipWhile(i => i != target)
        .Skip(1)
        .FirstOrDefault();
}

The n-ith element should be the same logic.  This is the actually first time I’ve used SkipWhile! You can use TakeWhile to do something similar, coming from the other end of the list.