This method removes n elements starting from a given index, from an array of a given type. If n is positive it removes elements forwards, if it is negative it removes them backwards (e.g. for an array {1,2,3,4,5} Remove(2,2) results in {1,2,5}; Remove (2,-2) results in {1,4,5})
It there a better way to do it?
public static class ArrayExtensions
{
public static T[] RemoveAt<T>(this T[] array, int idx, int len)
{
T[] newArray;
if (len > 0)
{
if (idx + len > array.Length)
len = array.Length - idx;
newArray = new T[array.Length - len];
if (idx > 0)
Array.Copy(array, 0, newArray, 0, idx);
if (idx < array.Length - 1)
Array.Copy(array, idx + len, newArray, idx, array.Length - idx - len);
}
else
{
newArray = new T[array.Length + len];
if (idx > 0)
Array.Copy(array, 0, newArray, 0, idx + len);
if (idx < array.Length - 1)
Array.Copy(array, idx, newArray, idx + len, array.Length - idx);
}
return newArray;
}
}
SkipWhile
andTakeWhile
with Linq, you could condense quite a bit. \$\endgroup\$