数组分为一维数组,多维数组(2维,3维),交错数组
创建数组实例后,其每个元素都有默认值,string 的为空字符串,int 的为 0 ,bool 的为 false,引用类型的为 null;
数组是数据的集合,标量变量一次只能保存一项。数组可以容纳多个项目,这些项目称为数组的元素,数组存储相同数据类型的数据,数组是引用类型。
int a = 10;// 一个数据
bool b = true; // 一个数据
每个元素都可以通过索引来引用、数组是从零开始的,第一个元素的索引为零。
// int[] 数据类型+[] , 3数组长度,可以明确指定,也可以不指定
// 没有初始化时,指定长度,有初始化时,长度省略。
int[] ints = new int[3];
ints[0] = 11;
ints[1] = 12;
ints[2] = 13;
//ints[3] = 14; // System.IndexOutOfRangeException:“索引超出了数组界限。”
数组一旦创建,长度固定,长度是只读的不能修改。
string[] strings = new string[] { "abc", "hello", "world" };
Console.WriteLine(strings.Length);
//strings.Length = 4;// Length长度是只读的不能修改
C#数组支持数组中存储不同数据类型的元素。如:object[]
object[] objects = new object[] { 1, 2, 'a', "hello", false, new object() { } };
1、一维数组
最简单、最常用的数组,在 C# 程序中使用 new 运算符实现一维数组,同时指定数组元素类型和元素数量。
Student[] students2 = {
new Student(){ Id=1,Name="张三1"},
new Student(){ Id=2,Name="张三2"},
new Student(){ Id=3,Name="张三3"},
};
2、多维数组
多维数组就是在一维数组的基础上增加了维度,多维数组在声明和访问元素的方式和一维数组不同,但在实现和属性上跟一维数组没有本质的区别, 一维数组支持的操作多维数组也都支持。
int[,] num = new int[,] { {1, 2, 3}, {1, 2, 3} };
int d1 = num.GetLength(0);
int d2 = num.GetLength(1);
for (int i=0; i<d1; i++)
{
for (int j=0; j<d2; j++)
{
Console.WriteLine(num[i, j]);
}
}
如果要访问数组中的元素,就要在语句中声明和初始化一个数组,注意要在中括号内加逗号。
int[,] num = new int[,] { {1, 2, 3}, {1, 2, 3} };
int d1 = num.GetLength(0);
int d2 = num.GetLength(1);
3、数组的API
1、Append添加
arr = arr.Append(4).ToArray();
Console.WriteLine(arr[3]); // 4
2、Clear清除
int[] arr = { 1, 2, 3, 4, 5, 6 };
Array.Clear(arr, 1, 2);
foreach (int i in arr) {
Console.WriteLine(i); // 1 0 0 4 5 6
}
3、IndexOf查数组中的索引
int[] arr = { 1, 2, 3, 3, 4, 5, 6 };
Console.WriteLine(Array.IndexOf(arr, 0)); // -1
Console.WriteLine(Array.IndexOf(arr, 3)); // 2
4、FindIndex()(从左向右)查索引,比IndexOf()灵活
int[] arr = { 1, 2, 3, 3, 4, 5, 6 };
Console.WriteLine(Array.FindIndex(arr, 0)); // -1
Console.WriteLine(Array.FindIndex(arr, 3)); // 2
// IndexOf()查找某个元素所在索引(从左向右),找到返回索引,找不到返回-1
5、FindLastIndex()(从右向左)查索引,比IndexOf()灵活
int[] arr = { 1, 2, 3, 3, 4, 5, 6 };
Console.WriteLine(Array.FindLastIndex(arr, 0)); // -1
Console.WriteLine(Array.FindLastIndex(arr, 3)); // 2
6、LastIndexOf()查找某个元素所在索引(从右向左),找到返回索引,找不到返回-1
int[] arr = { 1, 2, 3, 3, 4, 5, 6 };
Console.WriteLine(Array.LastIndexOf(arr, 0));
Console.WriteLine(Array.LastIndexOf(arr, 3));
7、Reverse数组反转,会直接修改没有返回值
int[] arr = { 1, 2, 3, 4, 5, 6 };
Array.Reverse(arr);
foreach (int i in arr) {
Console.WriteLine(i); // 6 5 4 3 2 1
}
8、Sort数组排序,会直接修改没有返回值
int[] arr = { 1, 6, 5, 2, 3, 4 };
Array.Sort(arr);
foreach (int i in arr) {
Console.WriteLine(i); // 1 2 3 4 5 6
}
//如果需要降序排序可以使用Reverse方法来反转数组中元素的顺序
Array.Reverse(arr);
foreach (int i in arr) {
Console.WriteLine(i); // 6 5 4 3 2 1
}