如何使用Linq / C#在当前和当前列表中获取项目? [英] How to get the item before current and after current in a list with Linq / C#?
问题描述
有没有linq选项或者什么的?
我已经检查了enumarator,但只有一个moveNext不能设置当前。
快速示例: 项目是一个字典 项目是字典中的一个keyvaluepair
var match = false;
var save = new KeyValuePair< ExtendedProjectLightPlan,Page>();
var before = new KeyValuePair< ExtendedProjectLightPlan,Page>();
var after = new KeyValuePair< ExtendedProjectLightPlan,Page>();
foreach(var p在项目中)
{
before = save;
save = p;
if(match)
{
after = p;
break;
if(p.Key.Id == project.Key.Id)
{
match = true;
$ / code $ / $ p
没有什么内置的LINQ来做到这一点,但你可以很容易地编写自己的...这是一个实现,它使用.NET 4中的 Tuple
。它将返回n-2个项目对于最初有n个项目的序列,但是如果需要可以调整。
public IEnumerable (这个IEnumerable< T>源)
{
//实际上产生前两个以及当前的 - 这个
//比上一个和下一个,但它们相当于使用(IEnumerator< T> iterator = source.GetEnumerator())
{
if(!iterator.MoveNext())
{
收益率突破;
}
T lastButOne = iterator.Current;
if(!iterator.MoveNext())
{
yield break;
}
T previous = iterator.Current;
while(iterator.MoveNext())
{
T current = iterator.Current;
产量返回Tuple.Create(lastButOne,previous,current);
lastButOne =上一个;
上一个=当前;
$ b 请注意,根据LukeH的回答,字典是无序的...但希望上述将帮助你。
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;
}
}
解决方案 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.
这篇关于如何使用Linq / C#在当前和当前列表中获取项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!