移动数组中的元素c#

我有这个非常简单的数组,我希望能够移动一些项目。在c#中是否有任何内置工具来执行此操作? 如果没有,你有任何建议,如何做到这一点。

在例子中

var smallArray = new string[4]; smallArray[0] = "a"; smallArray[1] = "b"; smallArray[2] = "c"; smallArray[3] = "d"; 

并且让我说我想(以编程方式)移动索引2和0,创建

 smallArray[0] = "c"; smallArray[1] = "a"; smallArray[2] = "b"; smallArray[3] = "d"; 

谢谢。

编辑:好的,现在你已经改变了这个例子,没有任何内置的东西 – 写起来实际上有点痛苦……你需要考虑你将它“移动”的情况。例如,你在哪里“向下”移动它。 你想要unit testing,但我认为应该这样做……

 public void ShiftElement(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而不是数组,它允许您在特定索引处插入和删除。 这两个操作比仅复制相关部分更昂贵,但它更具可读性。

这是一个现有的问题:

C#数组移动项(非ArrayList / Generic List)

答案是:

 void MoveWithinArray(Array array, int source, int dest) { Object temp = array.GetValue(source); Array.Copy(array, dest, array, dest + 1, source - dest); array.SetValue(temp, dest); } 

这解决了我的问题

 var arr = new ArrayList { "a", "b", "c", "d", "e", "f" }; var first = arr[2]; //pass the value which you want move from var next = arr[5]; //pass the location where you want to place var m = 0; var k = arr.IndexOf(first, 0, arr.Count); m = arr.IndexOf(next, 0, arr.Count); if (k > m) { arr.Insert(m, first); arr.RemoveAt(k + 1); } else { arr.Insert(k, next); arr.RemoveAt(m + 1); } 

返回a,b,f,c,d,e

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SecondLargest { class ArraySorting { public static void Main() { int[] arr={5,0,2,1,0,44,0,9,1,0,23}; int[] arr2 = new int[arr.Length]; int arr2Index = 0; foreach (int item in arr) { if(item==0) { arr2[arr2Index] = item; arr2Index++; } } foreach (int item in arr) { if(item!=0) { arr2[arr2Index] = item; arr2Index++; } } foreach (int item in arr2) { Console.Write(item+" "); } Console.Read(); } } }