C# 数组c中的移动元素#
我有一个非常简单的数组,我希望能够在其中移动一些项目。c#中是否有内置的工具来实现这一点?如果没有,你对如何做有什么建议吗 举例来说C# 数组c中的移动元素#,c#,arrays,C#,Arrays,我有一个非常简单的数组,我希望能够在其中移动一些项目。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"; sm
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";
谢谢。编辑:好的,现在您已经更改了示例,没有内置的内容-实际上写起来有点痛苦。。。例如,你需要考虑你把它“向上”移动的情况。你可能需要单元测试,但我认为这应该可以做到
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;
}
public void ShiftElement(此T[]数组,int-oldIndex,int-newIndex)
{
//TODO:参数验证
if(oldIndex==newIndex)
{
return;//无操作
}
T tmp=数组[oldIndex];
如果(新索引<旧索引)
{
//需要将阵列的一部分向上移动以腾出空间
复制(数组,新索引,数组,新索引+1,旧索引-新索引);
}
其他的
{
//需要将阵列的一部分“向下”移动以填充间隙
复制(数组,oldIndex+1,数组,oldIndex,newIndex-oldIndex);
}
数组[newIndex]=tmp;
}
您可能应该考虑使用<代码>列表>代码>而不是一个数组,它允许您插入和移除特定索引。这两个操作的成本比只复制相关部分要高,但可读性要高得多。
这是一个存在的问题: 答案是: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();
}
}
}