How to create and manipulate arrays in C#?
In C#, you can create and manipulate arrays using the following methods:
- Create an array:
int[] numbers = new int[5]; // 创建一个包含5个整数的数组
string[] names = new string[3]; // 创建一个包含3个字符串的数组
- Initialize an array.
int[] numbers = {1, 2, 3, 4, 5}; // 初始化包含5个元素的整数数组
string[] names = {"Alice", "Bob", "Charlie"}; // 初始化包含3个字符串的数组
- Accessing elements of an array:
int[] numbers = {1, 2, 3, 4, 5};
Console.WriteLine(numbers[0]); // 输出数组中第一个元素的值,即1
- Change elements in the array.
int[] numbers = {1, 2, 3, 4, 5};
numbers[2] = 10; // 将数组中第三个元素修改为10
- Traverse the array.
int[] numbers = {1, 2, 3, 4, 5};
foreach (int num in numbers)
{
Console.WriteLine(num); // 输出数组中每个元素的值
}
- Get the length of the array.
int[] numbers = {1, 2, 3, 4, 5};
int length = numbers.Length; // 获取数组的长度,即5
- Using the methods and properties of an array:
int[] numbers = {1, 2, 3, 4, 5};
Array.Sort(numbers); // 对数组进行升序排序
int max = numbers.Max(); // 获取数组中的最大值
int index = Array.IndexOf(numbers, 3); // 查找数组中元素值为3的索引位置
The above are some basic methods for creating and manipulating arrays in C#. Hope it helps you.