How to get the item before current and after current in a dictionary with Linq / C#?

Item before 'current':

items.TakeWhile(x => x != current).LastOrDefault();

Item after 'current':

items.SkipWhile(x => x != current).Skip(1).FirstOrDefault();

Works well for integral types but will return default(T) at the ends of the sequence. It might be useful to cast the items to Nullable<T> so that before the first item, and after the last item return null instead.


Have you tried using IndexOf() and ElementAt() methods??

    Int32 index = list1.IndexOf(item);
    var itemPrev = list1.ElementAt(index - 1);
    var itemNext = list1.ElementAt(index + 1);

There's nothing built into LINQ to do this, but you could write your own fairly easily... here's an implementation which uses Tuple from .NET 4. It will return n-2 items for a sequence which originally has n items - but you could adjust that if necessary.

public IEnumerable<Tuple<T, T, T>> WithNextAndPrevious<T>
    (this IEnumerable<T> source)
{
    // Actually yield "the previous two" as well as the current one - this
    // is easier to implement than "previous and next" but they're equivalent
    using (IEnumerator<T> iterator = source.GetEnumerator())
    {
        if (!iterator.MoveNext())
        {
            yield break;
        }
        T lastButOne = iterator.Current;
        if (!iterator.MoveNext())
        {
            yield break;
        }
        T previous = iterator.Current;
        while (iterator.MoveNext())
        {
            T current = iterator.Current;
            yield return Tuple.Create(lastButOne, previous, current);
            lastButOne = previous;
            previous = current;
        }
    }        
}

Note that as per LukeH's answer, dictionaries are unordered... but hopefully the above will help you anyway.