c #遍历数组
一维数组使用for,二维以上数组遍历可以使用foreach(in)。foreach会顺序遍历数组中的所有元素。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace study1_repeat
{
class Program
{
static void Main(string[] args)
{
//遍历数组的几种方法
string[] arrayColor = { "red", "yellow", "green" };
for (int i = arrayColor.Length - 1; i >= 0; i--)
{
Console.WriteLine(arrayColor[i]);
}
for (int i = arrayColor.GetLowerBound(0); i <= arrayColor.GetUpperBound(0); i++)
{
Console.WriteLine(arrayColor.GetValue(i));
}
//GetLowerBound(0)获取数组中指定维度的下限,最小的,0表示一维数组
//GetUpperBound(0)获取数组中指定唯独的上限,最大的,0表示一维数组
//遍历即从最小到最大
//GetValue(i)获取指定的数据
foreach (string color in arrayColor)
{
Console.WriteLine(color);
}
Console.ReadLine();
//遍历多维数组
int[,] nums = { { 10, 20 }, { 20, 30 }, { 40, 50 } };
foreach (int i in nums) {
Console.WriteLine(i);
}
Console.ReadLine();
}
}
}
数组(Array)常用的方法
使用方法:
Array.IndexOf(intArr, value1);
数组的合并与拆分
使用Array.copy()方法
copy方法的两种重载
- Array.copy(数组1,数组2,长度);将数组1中的元素,从第一个开始复制指定长度的元素复制到数组2中
- Array.copy(数组1,指定索引,数组2,指定索引,长度);将第一个数组中的元素从指定的索引开始复制指定长度的元素,复制到第二个数组的相应的指定索引的位置中,可以实现数组合并的效果。
- 用Array.copy(数组1,指定索引,数组2,指定索引,长度);也可以实现拆分数组的效果。选取数组1中的一部分,添加到空的数组2中,形成一个拆分后的新数组。
使用时的注意
- 设置合并和拆分时的新数组时要提前设置好数组的元素量,否则会报错
- 这个数组的合并和拆分的过程实际上还是一个遍历的过程,并不能减少运算
- copy方法的第二个数组一般用一个设置好长度的空数组来接收元素。