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

I have a list of projects and if i select a project then i will give a option previous and next. I have add a quick code example but i hope there is a better / faster way to do this for example 500 projects.

Is there maybe a linq option or something ?

I have checked enumarator but that haves only a moveNext en can't set the current.

Quick example:

projects is a dictionary

project is a keyvaluepair that exists in the dictionary

var match = false;
var save = new KeyValuePair<ExtendedProjectLightPlan, Page>();
var before = new KeyValuePair<ExtendedProjectLightPlan, Page>();
var after = new KeyValuePair<ExtendedProjectLightPlan, Page>();
foreach (var p in projects)
{
    before = save;
    save = p;

    if (match)
    {
        after = p;
        break;
    }

    if (p.Key.Id == project.Key.Id)
    {
        match = true;
    }                
}

Answers


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.


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);

Need Your Help

Cassandra assynchronous execution in multiple processes blocking synchronous requests

python database cassandra multiprocessing cql

I have an application that reads a series of XML files containing logs of vehicles passages in a road. The application then processes each record, transform a few of the informations to match the

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.