Csharp中foreach的用法
时间: 2023-09-30 14:11:02 浏览: 164
foreach语句用于遍历集合或数组中的每个元素,其语法如下:
```
foreach (var item in collection)
{
// 对元素的操作
}
```
其中,`collection`可以是数组、List、Dictionary等集合类型,`item`表示集合中的每个元素,可以是任何类型的变量。
示例:
```csharp
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int num in numbers)
{
Console.WriteLine(num);
}
```
输出:
```
1
2
3
4
5
```
在foreach语句中,可以使用`break`和`continue`关键字来控制循环的执行流程,例如:
```csharp
foreach (int num in numbers)
{
if (num == 3)
break; // 跳出循环
if (num == 2)
continue; // 跳过本次循环
Console.WriteLine(num);
}
```
输出:
```
1
4
5
```
相关问题
list中foreach用法
好的,关于list中foreach用法,可以用以下代码演示:
```csharp
List<int> nums = new List<int>{1, 2, 3, 4, 5};
foreach(int num in nums)
{
Console.WriteLine(num);
}
```
输出结果为:
```
1
2
3
4
5
```
这个示例中,我们创建了一个List<int>类型的nums变量,并初始化了5个整数元素。然后,我们使用foreach循环遍历nums列表中的每个元素,并打印出来。最终的输出结果就是1,2,3,4,5。
c#中 linq foreach用法
在 C# 中使用 LINQ 的 `foreach` 语句可以迭代一个集合,如下所示:
```csharp
using System.Linq;
...
var numbers = new List<int> { 1, 2, 3, 4, 5 };
foreach (var number in numbers)
{
Console.WriteLine(number);
}
```
输出:
```
1
2
3
4
5
```
如果要使用 LINQ 过滤集合中的元素,可以使用 `Where` 方法,如下所示:
```csharp
using System.Linq;
...
var numbers = new List<int> { 1, 2, 3, 4, 5 };
foreach (var number in numbers.Where(n => n % 2 == 0))
{
Console.WriteLine(number);
}
```
输出:
```
2
4
```
在上面的代码中,`Where` 方法返回集合中所有偶数,然后使用 `foreach` 循环迭代它们并将它们打印出来。
阅读全文
相关推荐
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![7z](https://img-home.csdnimg.cn/images/20241231044736.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)