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
相关推荐
吴可可1232 分钟前
用Teigha修改并保存CAD文件
数据库·算法·c#
老鱼说AI43 分钟前
统计学习方法第一章讲解:统计与监督学习概率
人工智能·学习·学习方法
他们叫我阿冠1 小时前
Day5学习--SpringBoot详解
spring boot·后端·学习
tedcloud1231 小时前
hello-agents部署教程:从零学习AI Agent开发
服务器·人工智能·学习·自动化·powerpoint
我想我不够好。1 小时前
针对性抓人 随机应变
学习
OSwich2 小时前
【 Godot 4 学习笔记】命名规范
笔记·学习·godot
觅_2 小时前
前端学习后端的时候 选择一个技术
前端·学习
吃吃今天努力学习了吗2 小时前
【大模型入门学习笔记】常见概念总结
笔记·学习
xiaoshuaishuai82 小时前
C# 签名异常与Gas预估失败调试方案
开发语言·网络·tcp/ip·c#
xiaoshuaishuai82 小时前
C# Gemini 辅助网络安全漏洞分析
开发语言·web安全·c#