C#(C Sharp)学习笔记_数组的遍历【十】

输出数组内容

  1. 一般而言,我们会使用索引来输出指定的内容。
csharp 复制代码
int[] arrayInt = new int[]  {4, 5, 2, 7, 9};
Console.WriteLine(arrayInt[3]);
  1. 但这样只能输出指定的索引指向的内容,无法一下子查看数组全部的值。
  2. 所以我们需要用到遍历方法输出所有元素。

几种常用的遍历方法

1. foreach( )

  1. forach十分适合用作遍历数组,因为语法很简单。
  2. 用过Python的都知道,它就相当于是Python语言中的for循环语句,当然,在C#中它也可以算作是一种循环语句。
  3. 它的具体流程是将数组内的元素,迭代给临时变量,每执行一次迭代一个元素给临时变量,直到全部迭代完成
csharp 复制代码
foreach (Type in Collection) {}
  1. 看下面的案例:
csharp 复制代码
int[] arrayInt = new int[]  {4, 5, 2, 7, 9};

foreach (int temp in  arrayInt) 
{
	 Console.WriteLine(temp);
}

// 运行结果:

csharp 复制代码
>>>4
>>>5
>>>2
>>>7
>>>9

2. For

  1. 其实用于遍历的主要就是循环语句。
  2. for语句我们可以通过编写特定程序,也能够实现遍历。
  3. 直接看实例吧:
csharp 复制代码
for (int temp = 0; temp < arrayInt.Length; temp++)
{
	 Console.WriteLine(arrayInt[temp]);
}

// 运行结果:

csharp 复制代码
>>>4
>>>5
>>>2
>>>7
>>>9
  1. 其中:.Length是一种方法,用于获取各种容器中的长度。我们通过循环,将索引叠加,直到无法满足大于该长度即可。

3. While

  1. while遍历数组的原理和for一样,其实没必要用while语句
csharp 复制代码
int[] arrayInt = new int[]  {4, 5, 2, 7, 9};

int temp = 0;
while (true) 
{
	Console.WriteLine(arrayInt[temp]);
	if (temp > arrayInt.Length) 
	{
		break;
	}
	else
	{
		temp ++;
    }
}

// 运行结果:

csharp 复制代码
>>>4
>>>5
>>>2
>>>7
>>>9
相关推荐
小小洋洋1 小时前
BLE MESH学习1-基于沁恒CH582学习
学习
Ace'2 小时前
每日一题&&学习笔记
笔记·学习
IM_DALLA2 小时前
【Verilog学习日常】—牛客网刷题—Verilog进阶挑战—VL25
学习·fpga开发·verilog学习
丶Darling.2 小时前
LeetCode Hot100 | Day1 | 二叉树:二叉树的直径
数据结构·c++·学习·算法·leetcode·二叉树
5967851544 小时前
DotNetty ChannelRead接收数据为null
tcp/ip·c#
z樾4 小时前
Github界面学习
学习
道爷我悟了5 小时前
Vue入门-指令学习-v-html
vue.js·学习·html
weixin_464078075 小时前
C#串口温度读取
开发语言·c#
计算机学姐6 小时前
基于SpringBoot+Vue的在线投票系统
java·vue.js·spring boot·后端·学习·intellij-idea·mybatis
彤银浦6 小时前
python学习记录7
python·学习