数组 C# 中的移位元素,不带数组帮助程序

  • 本文关键字:数组 帮助程序 元素 c#
  • 更新时间 :
  • 英文 :


我有一个数组,我想在没有任何辅助数组的情况下将其元素向左移动......我该怎么做?我试图这样做,但我认为这不是最好的方法......a1 是一个我想移动其元素的数组

for (int i = 0; i < a1.Length ; i++)
{
    foreach (var element in a1)
    {
        current = element;
        next = a1[i];
        next = current;
    }
    current = a1[i];
    next = a1[i + 1];
    a1[i] = next;
}

如果向左移动,你的意思是移动到顶部,那么这将是一个解决方案:

for(int i = 1; i < array.Length; i++){
  array[i-1] = array[i];
}
array[array.Length-1] = 0; // default value

它可能会有所帮助:

//say you have array a1
var first_element = a1[0];
//now you can shift element_2 to position_1 without fear of
//loosing first_element
for(int i=0;i<a1.Length-1;i++)
{
   a1[i] = a1[i+1];
} 
//shift first_element to last place.
a1[a1.Length-1] = first_element;

最新更新