Suppose there is an array with a specified length. How can we resize it? The easiest way to scale up is as follows:
class Program
{ static void Main(string[] args)
{ int[] arrs = new[] {1, 2, 3, 4, 5}; arrs[5] = 6;
}
}
Error: indexoutofranageexception is not processed, and the index exceeds the array limit.
□Create a temporary expanded array and assign it to the original array.
static void Main(string[] args)
{ int[] arrs = new[] {1, 2, 3, 4, 5}; int[] temp = new int[arrs.Length + 1];
// Traverse the arrs array and assign all elements of the array to the temp Array
for (int i = 0; i < arrs.Length; i++)
{ temp[i] = arrs[i];
}
// Assign a temporary array to the original array, and the original array has been expanded.
arrs = temp;
// Assign a value to the last position of the original array after expansion
arrs[arrs.Length - 1] = 6;
foreach (var item in arrs)
{ Console.WriteLine(item);
}
Console.ReadKey();
}
□Create a temporary array for expansion, assign a value to the original array, and use the static method of Array
For normal copying between arrays, the array class must have prepared a static method: array. Copy ().
static void Main(string[] args)
{ int[] arrs = new[] {1, 2, 3, 4, 5}; int[] temp = new int[arrs.Length + 1];
Array.Copy(arrs, temp, arrs.Length);
// Assign a temporary array to the original array, and the original array has been expanded.
arrs = temp;
// Assign a value to the last position of the original array after expansion
arrs[arrs.Length - 1] = 6;
foreach (var item in arrs)
{ Console.WriteLine(item);
}
Console.ReadKey();
}
□Use the static method of array to resize
However, copying and copying are cumbersome. We can also use the array. Resize () method to resize the array.
static void Main(string[] args)
{ int[] arrs = new[] {1, 2, 3, 4, 5}; Array.Resize(ref arrs, arrs.Length + 1);
// Assign a value to the last position of the original array after expansion
arrs[arrs.Length - 1] = 6;
foreach (var item in arrs)
{ Console.WriteLine(item);
}
Console.ReadKey();
}
Summary: array expansion gives priority to the use of the static method of array resize, and secondly, to assign a temporary and expanded array to the original array.
Several Methods to resize an array