c# 数组的使用

一、简述

        您可以在数组数据结构中存储相同类型的多个变量。您可以通过指定数组元素的类型来声明数组。如果您希望数组存储任何类型的元素,您可以指定object其类型。在 C# 的统一类型系统中,所有类型(预定义的和用户定义的、引用类型和值类型)都直接或间接继承自Object。

type[] arrayName;

        数组具有以下属性:

        1、数组可以是单维、多维或锯齿状的。

        2、维数是在声明数组变量时设置的。

        3、每个维度的长度是在创建数组实例时确定的。这些值在实例的生命周期内无法更改。

        4、交错数组是数组的数组,每个成员数组都有默认值null。

        5、数组的索引为零:包含n元素的数组的索引从0到n-1。

        6、数组元素可以是任何类型,包括数组类型。

        7、数组类型是从抽象基类型Array派生的引用类型。所有数组都实现IList和IEnumerable。您可以使用foreach语句来迭代数组。一维数组还实现IList<T>和IEnumerable<T>。 

        创建数组时,可以将数组的元素初始化为已知值。从 C# 12 开始,所有集合类型都可以使用Collection 表达式进行初始化。未初始化的元素将设置为默认值。默认值是 0 位模式。所有引用类型(包括不可为 null 的类型)都具有值null。所有值类型都具有 0 位模式。这意味着Nullable<T>.HasValue属性是false,而Nullable<T>.Value属性未定义。在 .NET 实现中,该Value属性会引发异常。

二、数组创建示例

// Declare a single-dimensional array of 5 integers.
int[] array1 = new int[5];// Declare and set array element values.
int[] array2 = [1, 2, 3, 4, 5, 6];// Declare a two dimensional array.
int[,] multiDimensionalArray1 = new int[2, 3];// Declare and set array element values.
int[,] multiDimensionalArray2 = { { 1, 2, 3 }, { 4, 5, 6 } };// Declare a jagged array.
int[][] jaggedArray = new int[6][];// Set the values of the first array in the jagged array structure.
jaggedArray[0] = [1, 2, 3, 4];

1、一维数组

        一维数组是相似元素的序列。您可以通过索引访问元素。索引是其在序列中的顺序位置。数组中的第一个元素位于索引处0。您可以使用指定数组元素类型和元素数量的new运算符创建一维数组。以下示例声明并初始化一维数组:

int[] array = new int[5];
string[] weekDays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];Console.WriteLine(weekDays[0]);
Console.WriteLine(weekDays[1]);
Console.WriteLine(weekDays[2]);
Console.WriteLine(weekDays[3]);
Console.WriteLine(weekDays[4]);
Console.WriteLine(weekDays[5]);
Console.WriteLine(weekDays[6]);/*Output:
Sun
Mon
Tue
Wed
Thu
Fri
Sat
*/

        第一个声明声明了一个由五个整数组成的未初始化数组,从array[0]到array[4]。数组的元素被初始化为元素类型的默认值0(对于整数)。第二个声明声明一个字符串数组并初始化该数组的所有七个值。foreach语句迭代数组的元素weekday并打印所有值。对于一维数组,该foreach语句按递增索引顺序处理元素,从索引 0 开始,以索引 结束Length - 1。

2、传递一维数组作为参数

        您可以将初始化的一维数组传递给方法。在以下示例中,初始化了一个字符串数组,并将其作为参数传递给DisplayArray字符串方法。该方法显示数组的元素。接下来,该ChangeArray方法反转数组元素,然后该ChangeArrayElements方法修改数组的前三个元素。每个方法返回后,该DisplayArray方法都会显示按值传递数组不会阻止对数组元素的更改。

class ArrayExample
{static void DisplayArray(string[] arr) => Console.WriteLine(string.Join(" ", arr));// Change the array by reversing its elements.static void ChangeArray(string[] arr) => Array.Reverse(arr);static void ChangeArrayElements(string[] arr){// Change the value of the first three array elements.arr[0] = "Mon";arr[1] = "Wed";arr[2] = "Fri";}static void Main(){// Declare and initialize an array.string[] weekDays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];// Display the array elements.DisplayArray(weekDays);Console.WriteLine();// Reverse the array.ChangeArray(weekDays);// Display the array again to verify that it stays reversed.Console.WriteLine("Array weekDays after the call to ChangeArray:");DisplayArray(weekDays);Console.WriteLine();// Assign new values to individual array elements.ChangeArrayElements(weekDays);// Display the array again to verify that it has changed.Console.WriteLine("Array weekDays after the call to ChangeArrayElements:");DisplayArray(weekDays);}
}
// The example displays the following output:
//         Sun Mon Tue Wed Thu Fri Sat
//
//        Array weekDays after the call to ChangeArray:
//        Sat Fri Thu Wed Tue Mon Sun
//
//        Array weekDays after the call to ChangeArrayElements:
//        Mon Wed Fri Wed Tue Mon Sun

3、多维数组

        数组可以有多个维度。例如,以下声明创建四个数组:两个具有二维,两个具有三个维度。前两个声明声明每个维度的长度,但不初始化数组的值。后两个声明使用初始值设定项来设置多维数组中每个元素的值。

int[,] array2DDeclaration = new int[4, 2];int[,,] array3DDeclaration = new int[4, 2, 3];// Two-dimensional array.
int[,] array2DInitialization =  { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
// Three-dimensional array.
int[,,] array3D = new int[,,] { { { 1, 2, 3 }, { 4,   5,  6 } },{ { 7, 8, 9 }, { 10, 11, 12 } } };// Accessing array elements.
System.Console.WriteLine(array2DInitialization[0, 0]);
System.Console.WriteLine(array2DInitialization[0, 1]);
System.Console.WriteLine(array2DInitialization[1, 0]);
System.Console.WriteLine(array2DInitialization[1, 1]);System.Console.WriteLine(array2DInitialization[3, 0]);
System.Console.WriteLine(array2DInitialization[3, 1]);
// Output:
// 1
// 2
// 3
// 4
// 7
// 8System.Console.WriteLine(array3D[1, 0, 1]);
System.Console.WriteLine(array3D[1, 1, 2]);
// Output:
// 8
// 12// Getting the total count of elements or the length of a given dimension.
var allLength = array3D.Length;
var total = 1;
for (int i = 0; i < array3D.Rank; i++)
{total *= array3D.GetLength(i);
}
System.Console.WriteLine($"{allLength} equals {total}");
// Output:
// 12 equals 12

        对于多维数组,遍历元素时首先递增最右侧维度的索引,然后递增下一个左侧维度,依此类推,直至最左侧索引。以下示例枚举 2D 和 3D 数组:

int[,] numbers2D = { { 9, 99 }, { 3, 33 }, { 5, 55 } };foreach (int i in numbers2D)
{System.Console.Write($"{i} ");
}
// Output: 9 99 3 33 5 55int[,,] array3D = new int[,,] { { { 1, 2, 3 }, { 4,   5,  6 } },{ { 7, 8, 9 }, { 10, 11, 12 } } };
foreach (int i in array3D)
{System.Console.Write($"{i} ");
}
// Output: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12

        在二维数组中,您可以将左索引视为行,将右索引视为列。 但是,对于多维数组,使用嵌套for循环可以让您更好地控制处理数组元素的顺序:

int[,,] array3D = new int[,,] { { { 1, 2, 3 }, { 4,   5,  6 } },{ { 7, 8, 9 }, { 10, 11, 12 } } };for (int i = 0; i < array3D.GetLength(0); i++)
{for (int j = 0; j < array3D.GetLength(1); j++){for (int k = 0; k < array3D.GetLength(2); k++){System.Console.Write($"{array3D[i, j, k]} ");}System.Console.WriteLine();}System.Console.WriteLine();
}
// Output (including blank lines): 
// 1 2 3
// 4 5 6
// 
// 7 8 9
// 10 11 12
//

4、将多维数组作为参数传递

        将初始化的多维数组传递给方法的方式与传递一维数组的方式相同。以下代码显示了 print 方法的部分声明,该方法接受二维数组作为其参数。您可以一步初始化并传递一个新数组,如以下示例所示。在以下示例中,初始化了一个二维整数数组并将其传递给该Print2DArray方法。该方法显示数组的元素。

static void Print2DArray(int[,] arr)
{// Display the array elements.for (int i = 0; i < arr.GetLength(0); i++){for (int j = 0; j < arr.GetLength(1); j++){System.Console.WriteLine("Element({0},{1})={2}", i, j, arr[i, j]);}}
}
static void ExampleUsage()
{// Pass the array as an argument.Print2DArray(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } });
}
/* Output:Element(0,0)=1Element(0,1)=2Element(1,0)=3Element(1,1)=4Element(2,0)=5Element(2,1)=6Element(3,0)=7Element(3,1)=8
*/

5、交错数组

        交错数组是一种其元素为数组且大小可能不同的数组。锯齿状数组有时称为“数组的数组”。它的元素是引用类型并初始化为null. 以下示例演示如何声明、初始化和访问交错数组。

        第一个示例jaggedArray是在一条语句中声明的。每个包含的数组都是在后续语句中创建的。

        第二个示例jaggedArray2是在一条语句中声明和初始化的。可以混合锯齿状数组和多维数组。

        最后一个示例jaggedArray3是一个单维交错数组的声明和初始化,该数组包含三个不同大小的二维数组元素。

int[][] jaggedArray = new int[3][];jaggedArray[0] = [1, 3, 5, 7, 9];
jaggedArray[1] = [0, 2, 4, 6];
jaggedArray[2] = [11, 22];int[][] jaggedArray2 = 
[[1, 3, 5, 7, 9],[0, 2, 4, 6],[11, 22]
];// Assign 77 to the second element ([1]) of the first array ([0]):
jaggedArray2[0][1] = 77;// Assign 88 to the second element ([1]) of the third array ([2]):
jaggedArray2[2][1] = 88;int[][,] jaggedArray3 =
[new int[,] { {1,3}, {5,7} },new int[,] { {0,2}, {4,6}, {8,10} },new int[,] { {11,22}, {99,88}, {0,9} }
];Console.Write("{0}", jaggedArray3[0][1, 0]);
Console.WriteLine(jaggedArray3.Length);

        交错数组的元素必须先初始化,然后才能使用它们。每个元素本身就是一个数组。还可以使用初始值设定项来用值填充数组元素。使用初始值设定项时,不需要数组大小。

        此示例构建一个数组,其元素本身就是数组。每个数组元素都有不同的大小。

// Declare the array of two elements.
int[][] arr = new int[2][];// Initialize the elements.
arr[0] = [1, 3, 5, 7, 9];
arr[1] = [2, 4, 6, 8];// Display the array elements.
for (int i = 0; i < arr.Length; i++)
{System.Console.Write("Element({0}): ", i);for (int j = 0; j < arr[i].Length; j++){System.Console.Write("{0}{1}", arr[i][j], j == (arr[i].Length - 1) ? "" : " ");}System.Console.WriteLine();
}
/* Output:Element(0): 1 3 5 7 9Element(1): 2 4 6 8
*/

6、隐式类型数组

        您可以创建一个隐式类型数组,其中数组实例的类型是根据数组初始值设定项中指定的元素推断出来的。任何隐式类型变量的规则也适用于隐式类型数组。        

        以下示例展示了如何创建隐式类型数组:

int[] a = new[] { 1, 10, 100, 1000 }; // int[]// Accessing array
Console.WriteLine("First element: " + a[0]);
Console.WriteLine("Second element: " + a[1]);
Console.WriteLine("Third element: " + a[2]);
Console.WriteLine("Fourth element: " + a[3]);
/* Outputs
First element: 1
Second element: 10
Third element: 100
Fourth element: 1000
*/var b = new[] { "hello", null, "world" }; // string[]// Accessing elements of an array using 'string.Join' method
Console.WriteLine(string.Join(" ", b));
/* Output
hello  world
*/// single-dimension jagged array
int[][] c =
[[1,2,3,4],[5,6,7,8]
];
// Looping through the outer array
for (int k = 0; k < c.Length; k++)
{// Looping through each inner arrayfor (int j = 0; j < c[k].Length; j++){// Accessing each element and printing it to the consoleConsole.WriteLine($"Element at c[{k}][{j}] is: {c[k][j]}");}
}
/* Outputs
Element at c[0][0] is: 1
Element at c[0][1] is: 2
Element at c[0][2] is: 3
Element at c[0][3] is: 4
Element at c[1][0] is: 5
Element at c[1][1] is: 6
Element at c[1][2] is: 7
Element at c[1][3] is: 8
*/// jagged array of strings
string[][] d =
[["Luca", "Mads", "Luke", "Dinesh"],["Karen", "Suma", "Frances"]
];// Looping through the outer array
int i = 0;
foreach (var subArray in d)
{// Looping through each inner arrayint j = 0;foreach (var element in subArray){// Accessing each element and printing it to the consoleConsole.WriteLine($"Element at d[{i}][{j}] is: {element}");j++;}i++;
}
/* Outputs
Element at d[0][0] is: Luca
Element at d[0][1] is: Mads
Element at d[0][2] is: Luke
Element at d[0][3] is: Dinesh
Element at d[1][0] is: Karen
Element at d[1][1] is: Suma
Element at d[1][2] is: Frances
*/

        在前面的示例中,请注意,对于隐式类型数组,初始化语句的左侧没有使用方括号。此外,交错数组的初始化方式与new []一维数组类似。

        当您创建包含数组的匿名类型时,该数组必须在该类型的对象初始值设定项中隐式类型化。在以下示例中,contacts是一个匿名类型的隐式类型数组,每个匿名类型都包含一个名为 的数组PhoneNumbers。该var关键字不在对象初始值设定项内部使用。

var contacts = new[]
{new{Name = "Eugene Zabokritski",PhoneNumbers = new[] { "206-555-0108", "425-555-0001" }},new{Name = "Hanying Feng",PhoneNumbers = new[] { "650-555-0199" }}
};

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/739799.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

docker搭建odoo16开发环境

要使用Docker搭建Odoo 16的开发环境&#xff0c;我们需要准备两个主要文件&#xff1a;一个是docker-compose.yml文件&#xff0c;用来定义和运行多个Docker应用容器&#xff0c;包括Odoo 16和PostgreSQL 15&#xff1b;另一个是odoo.conf文件&#xff0c;用来配置Odoo应用。下…

Vue2利用创建a标签实现下载本地静态文件到本地电脑上的功能

最近PC项目遇到一个需求&#xff0c;那就是需要前端下载前端代码包里的前端文件到本地&#xff0c;并且可以给下载下来的文件名指定任意的文件名&#xff0c;如下图所示&#xff0c;在前端代码里public里的statics里有个静态文件zswj.pem&#xff0c;页面上有个下载按钮&#x…

CPU设计实战-协处理器访问指令的实现

目录 一 协处理器的作用与功能 1.计数寄存器和比较寄存器 2.Status寄存器 3.Cause寄存器(标号为13) 4.EPC寄存器(标号为14) 5.PRId寄存器(标号为15) 6.Config 寄存器(标号为16)-配置寄存器 二 协处理器的实现 三 协处理器访问指令说明 四 具体实现 1.译码阶段 2.执行…

lqb省赛日志[4/37]

一只小蒟蒻备考蓝桥杯的日志 文章目录 笔记遍历 (DFS主题) 刷题心得小结 笔记 遍历 (DFS主题) 参考 BFS 的使用场景&#xff1a;层序遍历、最短路径问题 DFS -> 层次遍历 -> 无权图的最短路径 (Dijkstra 算法平替) 实现: 用队列存储, 出队, 孩子进队 隐式图遍历: 华…

Linux纯命令行查看文本文件

处理超大文本文件时&#xff0c;你可能希望避免一次性加载整个文件&#xff0c;这可能会耗尽内存资源。以下是一些在命令行中查看大文本文件的方法&#xff0c;它们适用于Linux和Unix系统&#xff0c;包括Mac OS X&#xff0c;而在Windows中&#xff0c;你可以使用类似的工具或…

初阶数据结构之---堆的应用(堆排序和topk问题)

引言 上篇博客讲到了堆是什么&#xff0c;以及堆的基本创建和实现&#xff0c;这次我们再来对堆这个数据结构更进一步的深入&#xff0c;将讲到的内容包括&#xff1a;向下调整建堆&#xff0c;建堆的复杂度计算&#xff0c;堆排序和topk问题。话不多说&#xff0c;开启我们今…

新智元 | Stable Diffusion 3技术报告流出,Sora构架再立大功!生图圈开源暴打Midjourney和DALL·E 3?

本文来源公众号“新智元”&#xff0c;仅用于学术分享&#xff0c;侵权删&#xff0c;干货满满。 原文链接&#xff1a;Stable Diffusion 3技术报告流出&#xff0c;Sora构架再立大功&#xff01;生图圈开源暴打Midjourney和DALLE 3&#xff1f; 【新智元导读】Stability AI放…

1.Python是什么?——跟老吕学Python编程

1.Python是什么&#xff1f;——跟老吕学Python编程 Python是一种什么样的语言&#xff1f;Python的优点Python的缺点 Python发展历史Python的起源Python版本发展史 Python的价值学Python可以做什么职业&#xff1f;Python可以做什么应用&#xff1f; Python是一种什么样的语言…

网络触手获取天气数据存入mysql 项目

首先这个案例不一定能直接拿来用&#xff0c;虽然我觉得可以但是里面肯定有一些我没考虑到的地方。 有问题评论或者私信我&#xff1a; 这个案例适合我这种学生小白 获取天气数据网址&#xff1a; https://lishi.tianqi.com/xianyang/202201.html 网络触手获取天气数据代码直…

c++两种去重方法(erase+unique 和 unique)

一&#xff0c;eraseunique 适用于容器如 vector。 1.代码&#xff1a; vector<int> v;//使用unique前必须排序&#xff08;他只能删除相邻相同的元素&#xff0c;背过即可&#xff09;sort(v.begin(),v.end());// unique(v.begin(),v.end())返回的是不重复元素的下一个…

分布式事务模式:AT、TCC、Saga、XA模式

AT模式 2PC使用二阶段提交协议&#xff1a;Prepare提交事务请求&#xff0c; 我认为就是执行分布式的方法&#xff0c;当所有方法都执行完毕&#xff0c;且没有错误&#xff0c;也就是ack为yes。然后开始第二阶段&#xff1a; commit:提交事务 TCC模式和消息队列模式&#x…

[软件工具]yolo实例分割数据集转labelme的json格式

软件界面&#xff1a; YOLO实例分割数据集转LabelMe JSON格式软件是一款功能强大的数据转换工具&#xff0c;旨在将YOLO&#xff08;You Only Look Once&#xff09;实例分割数据集转换为LabelMe的JSON格式&#xff0c;以满足不同图像标注软件之间的数据共享需求。 该软件具有…

前端面试-浏览器相关

文章目录 1 浏览器安全1.1 什么是 XSS 攻击&#xff1f;1. 概念2. 攻击类型 1.2 如何防御 XSS 攻击&#xff1f;1.3 什么是 CSRF 攻击&#xff1f;1. 概念2. 攻击类型 1.4 如何防御 CSRF 攻击&#xff1f;1.5 什么是中间人攻击&#xff1f;如何防范中间人攻击&#xff1f;1.6 哪…

图论(二)之最短路问题

最短路 Dijkstra求最短路 文章目录 最短路Dijkstra求最短路栗题思想题目代码代码如下bellman-ford算法分析只能用bellman-ford来解决的题型题目完整代码 spfa求最短路spfa 算法思路明确一下松弛的概念。spfa算法文字说明&#xff1a;spfa 图解&#xff1a; 题目完整代码总结ti…

基于SpringBoot的“医院信管系统”的设计与实现(源码+数据库+文档+PPT)

基于SpringBoot的“医院信管系统”的设计与实现&#xff08;源码数据库文档PPT) 开发语言&#xff1a;Java 数据库&#xff1a;MySQL 技术&#xff1a;SpringBoot 工具&#xff1a;IDEA/Ecilpse、Navicat、Maven 系统展示 功能结构图 系统首页界面图 用户注册界面图 医生…

BUG:RuntimeError: input.size(-1) must be equal to input_size. Expected 1, got 3

出现的bug为:RuntimeError: input.size(-1) must be equal to input_size. Expected 1, got 3 出现问题的截图: 问题产生原因:题主使用pytorch调用的nn.LSTM里面的input_size和外面的数据维度大小不对。问题代码如下: self.lstm nn.LSTM(input_size, hidden_size, num_laye…

PyTorch学习笔记(三)

2.4 获取tensor中元素的数量 在PyTorch中&#xff0c;如果你有一个tensor&#xff08;张量&#xff09;&#xff0c;你可以使用numel()函数来获取tensor中所有元素的数量。numel()会返回tensor中所有元素的数量&#xff0c;不考虑tensor的维度。 下面是一个例子&#xff1a; …

面向对象设计之依赖反转原则

设计模式专栏&#xff1a;http://t.csdnimg.cn/4Mt4u 目录 1.引言 2.控制反转(loC) 3.依赖注入(DI) 4.依赖注入框架(DlFramework) 5.依赖反转原则(DIP) 6.总结 1.引言 前面讲到&#xff0c;单一职责原则和开闭原则的原理比较简单&#xff0c;但在实践中用好比较难&#x…

干货!不懂Python的math模块和random模块操作还不赶紧来学!

1.导入math模块 import math 2.向上取整&#xff1a;math.ceil() num 9.12print(math.ceil(num)) # 10 3.向下取整&#xff1a;math.floor() num1 9.99print(math.floor(num1)) # 9 4.开平方&#xff1a;math.sqrt()​​​​​​​ num2 16print(math.sqrt(num…

算法打卡day8|字符串篇02|Leetcode 28. 找出字符串中第一个匹配项的下标、459. 重复的子字符串

算法题 Leetcode 28. 找出字符串中第一个匹配项的下标 题目链接:28. 找出字符串中第一个匹配项的下标 大佬视频讲解&#xff1a;KMP理论篇 KMP代码篇 个人思路 当看到在一个串中查找是否出现过另一个串&#xff0c;那肯定是用kmp算法了; kmp比较难理解,详细理论和代码可以…