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#程序设计有所帮助。


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3