在数组C#中移动元素 [英] Moving elements in array c#
问题描述
我有一个非常简单的数组,希望可以在其中移动某些项.在c#中是否有内置工具可以做到这一点?如果没有,那么您对此有任何建议.
I have this very simple array which I want to be able to move around some items in. Are there any built in tools in c# to do this? If not, du you have any suggestion in how to do it.
例如
var smallArray = new string[4];
smallArray[0] = "a";
smallArray[1] = "b";
smallArray[2] = "c";
smallArray[3] = "d";
并且可以说我想(以编程方式)移动索引2和0,创建
And lets say I want to (programmatically) shift index 2 and 0, creating
smallArray[0] = "c";
smallArray[1] = "a";
smallArray[2] = "b";
smallArray[3] = "d";
谢谢.
推荐答案
好的,现在您已经更改了示例,没有内置的内容-写起来实际上有点麻烦...例如,您需要考虑将其向上"移动和向下"移动的情况.您需要单元测试,但是我认为这应该做到...
Okay, now you've changed the example, there's nothing built-in - and it would actually be a bit of a pain to write... you'd need to consider cases where you're moving it "up" and where you're moving it "down", for example. You'd want unit tests, but I think this should do it...
public void ShiftElement<T>(this T[] array, int oldIndex, int newIndex)
{
// TODO: Argument validation
if (oldIndex == newIndex)
{
return; // No-op
}
T tmp = array[oldIndex];
if (newIndex < oldIndex)
{
// Need to move part of the array "up" to make room
Array.Copy(array, newIndex, array, newIndex + 1, oldIndex - newIndex);
}
else
{
// Need to move part of the array "down" to fill the gap
Array.Copy(array, oldIndex + 1, array, oldIndex, newIndex - oldIndex);
}
array[newIndex] = tmp;
}
您可能应该考虑使用List<T>
而不是数组,该数组允许您在特定索引处插入和删除.这两个操作比仅复制相关部分要昂贵得多,但可读性更高.
You should probably consider using a List<T>
instead of an array, which allows you to insert and remove at particular indexes. Those two operations will be more expensive than only copying the relevant section, but it'll be a lot more readable.
这篇关于在数组C#中移动元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!