Fork me on github

C# 中 foreach的用法 (补List 的 ForEach细节)

foreach有点像是for的增强版

在C#中有时候会遇到需要循环输出的情况,比如这样:

复制代码
using Syatem
using System.Collections;
using System.Collections.Generic;

class one {
    int[] A = { 1, 2, 3, 4, 5 };
    void Main()
    {
     //for
for (int i = 0; i < A.Length; i++) Console.WriteLine(A[i]);
     //foreach
foreach (int i in A) Console.WriteLine(i); } }
复制代码

可以看出,当不需要麻烦的操作的时候,不需要针对第 i 元素进行奇怪的操作时,foreach提高了写代码的整洁和效率;


注:

1.foreach中的 i 就是A中的元素,如果A是字符串,则应该写为

foreach (char i in A)
 Console.WriteLine(i);

2.不要在foreach中试图增删,这样会报异常!需使用for!

3.List中有一个ForEach,可以实现在循环内增删,关于此还有挺多可以说的:

  List中ForEach是有委托的:要对 Action<T> 的每个元素执行的 List<T> 委托

标准写法: public void ForEach (Action<T> action); ,然后官方给出了一个示例,由此就可以看出用法了:

复制代码
 1 using System;
 2 using System.Collections.Generic;
 3 
 4 class Program
 5 {
 6     static void Main()
 7     {
 8         List<String> names = new List<String>();
 9         names.Add("Bruce");
10         names.Add("Alfred");
11         names.Add("Tim");
12         names.Add("Richard");
13 
14         // Display the contents of the list using the Print method.
15         names.ForEach(Print);
16 
17         // The following demonstrates the anonymous method feature of C#
18         // to display the contents of the list to the console.
19         names.ForEach(delegate(String name)
20         {
21             Console.WriteLine(name);
22         });
23     }
24 
25     private static void Print(string s)
26     {
27         Console.WriteLine(s);
28     }
29 }
30 /* This code will produce output similar to the following:
31  * Bruce
32  * Alfred
33  * Tim
34  * Richard
35  * Bruce
36  * Alfred
37  * Tim
38  * Richard
39  */
点击查看全部示范代码
复制代码

by the way,此操作是O(n)操作。

posted @   未配妥剑,已入江湖  阅读(21513)  评论(1编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示