📜  C＃foreach循环

📅  最后修改于: 2020-10-06 09:29:00             🧑  作者: Mango

在本文中，我们将学习foreach循环(for循环的替代方法)以及如何将其与数组和集合一起使用。

C＃提供了一种易于使用且可读性强的替代方法for循环，即在处理数组和集合以遍历数组/集合项时使用的foreach循环。 foreach循环遍历每个项目，因此称为foreach循环。

• C＃for循环
• C＃数组
• C＃集合

foreach循环的语法
``````foreach (element in iterable-item)
{
// body of foreach loop
}
``````

foreach循环如何工作？

foreach循环将执行的次数等于数组或集合中元素的数量。

示例1：使用for循环打印数组
``````using System;

namespace Loop
{
class ForLoop
{
public static void Main(string[] args)
{
char[] myArray = {'H','e','l','l','o'};

for(int i = 0; i < myArray.Length; i++)
{
Console.WriteLine(myArray[i]);
}
}
}
}
``````

示例2：使用foreach循环打印数组
``````using System;

namespace Loop
{
class ForEachLoop
{
public static void Main(string[] args)
{
char[] myArray = {'H','e','l','l','o'};

foreach(char ch in myArray)
{
Console.WriteLine(ch);
}
}
}
}
``````

``````H
e
l
l
o
``````

示例3：使用foreach循环遍历性别数组

``````using System;

namespace Loop
{
class ForEachLoop
{
public static void Main(string[] args)
{
char[] gender = {'m','f','m','m','m','f','f','m','m','f'};
int male = 0, female = 0;
foreach (char g in gender)
{
if (g == 'm')
male++;
else if (g =='f')
female++;
}
Console.WriteLine("Number of male = {0}", male);
Console.WriteLine("Number of female = {0}", female);
}
}
}
``````

``````Number of male = 6
Number of female = 4
``````

示例4：带有列表(集合)的foreach循环

``````using System;
using System.Collections.Generic;

namespace Loop
{
class ForEachLoop
{
public static void Main(string[] args)
{
var numbers = new List() {5,-8,3,14,9,17,0,4};
int sum = 0;

foreach(int number in numbers)
{
sum += number;
}
Console.WriteLine("Sum = {0}", sum);
}
}
}
``````

``Sum = 44``