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
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.