我有一个实现 IEnumerable<T>
的列表类.
类型 T 是一个复杂类,以字符串成员作为唯一标识符。但仅以 int 作为元素类型来解释就足够了。
我想将多个项目向左移动一步。
示例:
原始列表:0、1、2、3、4、5 br/>
现在,所有粗体项 (0,3,4) 都应该向左移动(尽可能远)。
结果列表:0, 1, 3, 4, 2, 5
是否有好的算法可以做到这一点?也许只需要使用 LINQ。
编辑:List<T>
的答案名单是受欢迎的。我的类(class)有类似的方法。 (感谢 TylerOhlsen 的提示。)
Edit2:一个选定的项目不应超过另一个选定的项目。
最佳答案
这看起来可行:
public static IEnumerable<T> MoveSelectedLeft<T>(
this IEnumerable<T> source,
IEnumerable<int> indicesToMove /* must be in order! */)
{
using (var itm = indicesToMove.GetEnumerator())
{
bool hasNextToMove = itm.MoveNext();
int nextToMove = hasNextToMove ? itm.Current : -1;
bool canMoveYet = false;
T held = default(T);
int currentIndex = 0;
foreach (T t in source)
{
if (hasNextToMove && nextToMove == currentIndex)
{
hasNextToMove = itm.MoveNext();
nextToMove = hasNextToMove ? itm.Current : -1;
yield return t;
}
else
{
if (!canMoveYet)
{
canMoveYet = true;
}
else
{
yield return held;
}
held = t;
}
currentIndex++;
}
if (canMoveYet)
yield return held;
}
}
称为
foreach (int i in new[] { 0,1,2,3,4,5 }.MoveSelectedLeft(new[] { 0,3,4 }))
{
Console.WriteLine(i);
}
关于c# - 移动列表中的多个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13272894/