C# 语法 - Lambda 表达式示例 - ForEach() over Generic List [英] C# Syntax - Example of a Lambda Expression - ForEach() over Generic List
问题描述
首先,我知道框架中已有的通用 List<>
类的方法会迭代 List<>
.
First, I know there are methods off of the generic List<>
class already in the framework do iterate over the List<>
.
但举个例子,编写 ForEach 方法来迭代 List<>
的每个对象并执行 Console.WriteLine(object.ToString) 的正确语法是什么?())
在每个对象上.将 List<>
作为第一个参数,将 lambda 表达式作为第二个参数的东西.
But as an example, what is the correct syntax to write a ForEach method to iterate over each object of a List<>
, and do a Console.WriteLine(object.ToString())
on each object.
Something that takes the List<>
as the first argument and the lambda expression as the second argument.
我见过的大多数示例都是作为扩展方法完成的或涉及 LINQ.我正在寻找一个普通的方法示例.
Most of the examples I have seen are done as extension methods or involve LINQ. I'm looking for a plain-old method example.
推荐答案
public void Each<T>(IEnumerable<T> items, Action<T> action)
{
foreach (var item in items)
action(item);
}
...并这样称呼它:
Each(myList, i => Console.WriteLine(i));
这篇关于C# 语法 - Lambda 表达式示例 - ForEach() over Generic List的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!