将项目起来了IEnumerable [英] Move item up in IEnumerable
问题描述
我有必要在一个IEnumerable<移动项目;>,那就是移动在另一个上面一个项目。什么是最简单的方法是什么?
I have a need to move an item in an IEnumerable<> up, that is move one item above another. What is the simplest way to do this?
有一个类似的问题在这里问,但我没有一个通用的列表只是一个IEnumerable<>:http://stackoverflow.com/questions/450233/generic-list-moving-an-item-within-the-list
A similar question was asked here but I don't have a generic list only an IEnumerable<>: http://stackoverflow.com/questions/450233/generic-list-moving-an-item-within-the-list
推荐答案
由于@布赖恩评论,问题是作为在什么移动项目有点不清楚IEnumerable的<>高达
表示。
As @Brian commented the question is a little unclear as to what move an item in an IEnumerable<> up
means.
如果要重新排序一个IEnumerable为单个项目,然后下面的代码应该可能是你在找什么。
If you want to reorder an IEnumerable for a single item then the code below should might be what you are looking for.
public static IEnumerable<T> MoveUp<T>(this IEnumerable<T> enumerable, int itemIndex)
{
int i = 0;
IEnumerator<T> enumerator = enumerable.GetEnumerator();
while (enumerator.MoveNext())
{
i++;
if (itemIndex.Equals(i))
{
T previous = enumerator.Current;
if (enumerator.MoveNext())
{
yield return enumerator.Current;
}
yield return previous;
break;
}
yield return enumerator.Current;
}
while (enumerator.MoveNext())
{
yield return enumerator.Current;
}
}
这篇关于将项目起来了IEnumerable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!