How to get the item before current and after current in a list with Linq / C#? -
i have list of projects , if select project give option previous , next. have add quick code example hope there better / faster way example 500 projects.
is there maybe linq option or ?
i have checked enumarator haves movenext en can't set current.
quick example:
projects dictionary
project keyvaluepair exists in 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; } }
there's nothing built linq this, write own easily... here's implementation uses tuple
.net 4. return n-2 items sequence has n items - adjust if necessary.
public ienumerable<tuple<t, t, t>> withnextandprevious<t> (this ienumerable<t> source) { // yield "the previous two" current 1 - // easier implement "previous , next" 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 per lukeh's answer, dictionaries unordered... above anyway.
Comments
Post a Comment