How to shift the start of an array in C#?

后端 未结 8 1990
渐次进展
渐次进展 2020-12-18 07:31

I\'m trying to reorganize an array based on the first occurrence of a value (thus simulating similar functionality to a circular array.)

For example, in the followin

8条回答
  •  [愿得一人]
    2020-12-18 07:58

    New approach that will only work with .NET 4.5 (from 2012) or later:

      const int value = 6;
      int[] myArray = { 2, 3, 6, 1, 7, 6, };
    
      var index = Array.IndexOf(myArray, value);
      if (index == -1)
        throw new InvalidOperationException();
    
      var rotatedArray = (new ArraySegment(myArray, index, myArray.Length - index))
        .Concat(new ArraySegment(myArray, 0, index))
        .ToArray();
    

    In earlier .NET versions, an ArraySegment<> value could not be used as an IEnumerable<> like that.


    Not clear to me if it was a requirement that the original array instance be mutated, but if you need that, simply append:

      rotatedArray.CopyTo(myArray, 0);
    

    to my code.

提交回复
热议问题