C#---二维数组
1.有两个下标的数组称为二维数组
2.二维数组本质上是以数组作为数组元素的数组,即数组的数组
二维数组的初始化
动态初始化
类型[,] 数组名=new 类型[常量表达式1,常量表达式2];
例如:int[,] array=new int[2,3]{{1,2,3},{1,2,3}}
int[,] map=new int[,]{{1,2,3},{4,5,6}}
注意:第二维的个数必须相同,例如上面的写法会出现编译错误
using System;
namespace SecondArray
{
class Program
{
static void Main(string[] args)
{
int[] array = { 1, 2, 3, 4 };
int[][] newArray = { new int[] { 1, 3, 4, 5, 6 }, new int[] { 2, 4, 6, 8, 2 } };
//动态初始化
int[,] csharpArray = new int[3, 5];
int[,] maps = new int[,] { {3,5},{1,2},{2,4} };
Console.WriteLine(maps[2, 1]);
//获取二维数组的长度,相当于二维数组的元素个数(总长度)
Console.WriteLine(maps.Length);
//如何获取二维数组的长度
Console.WriteLine("0:" + maps.GetLength(0));
Console.WriteLine("1:" + maps.GetLength(1));
//二维数组的遍历
int[,] heroData = {
{3,0,0},
{0,5,0},
{1,0,2},
{0,1,3}
};
for (int i = 0; i < heroData.GetLength(0); i++) {
for (int j = 0; j < heroData.GetLength(1); j++) {
Console.Write(heroData[i, j]+"\t");
}
//换行
Console.WriteLine();
}
}
}
}
using System;
namespace SecondArray01
{
class Program
{
static void Main(string[] args)
{
int[,] heroData = {
{3,0,0},
{0,5,0},
{1,0,2},
{0,1,3}
};
//定义数组
int[,] dataStatistics = new int[heroData.GetLength(1),heroData.GetLength(0)];
for (int i = 0; i < heroData.GetLength(0); i++) {
for(int j = 0; j < heroData.GetLength(1); j++)
{
dataStatistics[j, i] = heroData[i, j];
}
}//遍历新数组
for (int i = 0; i < dataStatistics.GetLength(0); i++) {
for (int j = 0; j < dataStatistics.GetLength(1); j++) {
Console.Write(dataStatistics[i,j]+"\t");
}
Console.WriteLine();
}
}
}
}
迭代遍历foreach
foreack(迭代类型 迭代变量名 in 迭代集合){
//循环体
}
迭代类型:必须和后面的迭代集合匹配,也可以使用模糊数据类型var
迭代集合:可以是数组、字符串、集合等
using System;
namespace TestForeach
{
class Program
{
static void Main(string[] args)
{
int[] number = { 3, 5, 7, 9 };
foreach (var item in number)
{
Console.WriteLine(item);
}
}
}
}
底层消耗比for循环高
using System;
namespace TestForeach
{
class Program
{
static void Main(string[] args)
{
int[] number = { 3, 5, 7, 9 };
foreach (var item in number)
{
Console.WriteLine(item);
}
int[,] map = { { 0, 0, 0 }, { 1, 0, 3 }, { 5, 0, 8 }, { -1, 0, -2 } };
Console.WriteLine("foreach遍历二维数组");
foreach (var item in map) { Console.WriteLine(item); }
Console.WriteLine("foreach遍历string");
string str = "Hello,Unity!";
foreach (var item in str) {
Console.WriteLine(item);
}
}
}
}
更多推荐
所有评论(0)