软件编程
位置:首页>> 软件编程>> C#编程>> C#使用foreach语句遍历二维数组的方法

C#使用foreach语句遍历二维数组的方法

作者:heishui  发布时间:2023-01-19 22:06:05 

标签:C#,foreach,遍历,数组

本文实例讲述了C#使用foreach语句遍历二维数组的方法。分享给大家供大家参考。具体分析如下:

如果通过for语句循环遍历二维数组需要两重循环才可以,二foreach语句只需要一次可以完全遍历整个二维数组,下面是代码演示


using System;
public class w3demo{
public static void Main() {
 int sum = 0;
 int[,] nums = new int[3,5];
 // give nums some values
 for(int i = 0; i < 3; i++)
  for(int j=0; j < 5; j++)
   nums[i,j] = (i+1)*(j+1);
 //通过foreach语句计算nums数组中所有元素的和
 foreach(int x in nums) {
  Console.WriteLine("Value is: " + x);
  sum += x;
 }
 Console.WriteLine("Summation: " + sum);
}
}

希望本文所述对大家的C#程序设计有所帮助。

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com