【问题标题】:Moving a element of a ArrayList to the Front while keeping the order C#在保持顺序的同时将 ArrayList 的元素移到前面 C#
【发布时间】:2011-04-08 09:40:37
【问题描述】:

假设我有一个这样的数组,

The, Quick, Brown, Fox, Jumps 

我需要将其中一个元素移动/移动到前面,这样它看起来像这样

Brown, Fox, Jumps, The, Quick

如何像旋转门一样对数组进行排序?通过移动一个元素并让其余元素跟在后面?

有没有简单的方法或者我应该只是复制/循环/切片/复制?

【问题讨论】:

  • 此时,ArrayList 已过时。试试List<T>
  • @Steven Sudit:是的,除非你被限制在 <.net>
  • 数组还是数组列表?您的标题和问题正文彼此不一致。您的标签并没有使它更清晰。
  • @SnOrfus:鉴于 .NET 2.0 已经 5 年了,我希望这不是一个真正的问题。
  • Generics /ArrayList 或 Rec Array 没关系,哪种方式最简单,我也会尝试 List

标签: c# arrays arraylist


【解决方案1】:

您可以使用Array.Copy 来避免编写显式循环。以下代码创建一个新数组而不是修改原始数组:

T[] rotate<T>(T[] a, int index)
{
    T[] result = new T[a.Length];
    Array.Copy(a, index, result, 0, a.Length - index);
    Array.Copy(a, 0, result, a.Length - index, index);
    return result;
}

public void Run()
{
    string[] words = { "The", "Quick", "Brown", "Fox", "Jumps" };
    string[] result = rotate(words, 2);
    foreach (string word in result)
    {
        Console.WriteLine(word);
    }
}

【讨论】:

    【解决方案2】:

    看到这个How to shift the start of an array in C#?

            string[] myArray = { "The", "Quick", "Brown", "Fox", "Jumps" };
            myArray = myArray.SkipWhile(t => t != "Brown").Concat(myArray.TakeWhile(t => t != "Brown")).ToArray();
    

    【讨论】:

      【解决方案3】:
      ArrayList list = new ArrayList();
      list.Add("The");
      list.Add("Quick");
      list.Add("Brown");
      list.Add("Fox");
      list.Add("Jumps");
      
      ArrayList newList = new ArrayList();
      int index = 2;
      for (int i = index; i < list.Count; i++)
      {
          newList.Add(list[i]);
      }
      
      for (int i = 0; i < index; i++)
      {
          newList.Add(list[i]);
      }
      
      list = newList;
      

      【讨论】:

      • 哦,伙计,这太快了,我现在感觉自己像个白痴,这比我打算做的要简单得多。谢谢
      【解决方案4】:

      试试下面的方法

      public void ShiftRevolvingDoor(ArrayList list, int count) {
        while ( count > 0 ) {
          ShiftRevolvingDoor(list);
          count--;
        }
      }
      
      public void ShiftRevolvingDoor(ArrayList list) {
        if ( list.Count < 2 ) {
          return;
        }
        int lastIndex = list.Count - 1;
        object first = list[0];
        for ( i = 0; i < lastIndex; i++) {
          list[i] = list[i+1];
        }
        list[lastIndex] = first;
      }
      

      【讨论】:

        猜你喜欢
        • 2021-10-18
        • 2021-02-03
        • 1970-01-01
        • 2015-08-25
        • 2015-04-21
        • 1970-01-01
        • 1970-01-01
        • 2016-01-14
        • 2012-02-24
        相关资源
        最近更新 更多