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
相关推荐
rockey6272 小时前
基于AScript的Lua脚本语言发布啦
c#·.net·lua·script·动态脚本
IT古董2 小时前
【MES学习笔记系列】MES 厂商与产品对比
笔记·学习
wangyue_msn_862 小时前
Agent知识学习笔记——03 RAG
笔记·学习·ai编程
呱呱巨基3 小时前
Linux 查找命令
linux·笔记·学习·查找命令
zhangrelay4 小时前
ROS 2 Lyrical 第4章 URDF机器人建模与Gazebo Garden仿真
linux·笔记·学习·ubuntu·机器人·ros2
Dave1205464 小时前
AI Agent学习 Day14:LangGraph进阶 —— 条件分支、Tool Node与Memory持久化
人工智能·学习
半亩码田4 小时前
【.NET新特性·第11篇】C# 14 字段属性:告别手写 backing field
java·c#·.net
曹牧5 小时前
C#:问号
前端·数据库·c#
少控科技5 小时前
农场设备管理代码(2)
开发语言·c#
red_redemption5 小时前
自由学习记录(214)
学习