Alex Rivera | Logout

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

Asked 2010-12-02T11:21:33.710
15

I have a dictionary of projects and if I select a project then I will give an option previous and next. I have added a code example but I hope there is a better / faster way to do this e.g. for 500 projects.

Is there maybe a LINQ option or something?

I have checked Enumerator but it only has a moveNext method and 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;
    }                
}
Edit
Report

1 Answer

16

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);
answered 2010-12-02T11:24:09.717

Your Answer