C#语法 - 的LAMBDA前pression例子 - 的ForEach()在泛型列表 [英] C# Syntax - Example of a Lambda Expression - ForEach() over Generic List

查看:136
本文介绍了C#语法 - 的LAMBDA前pression例子 - 的ForEach()在泛型列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我知道有过普通的名单,其中的方法,已经在框架类做遍历名单,其中;&GT>

不过,作为一个例子,什么是正确的语法来写一个foreach方法以一个名单,其中,每一个对象迭代;> ,并做了 Console.WriteLine(object.ToString())每个对象上。 东西取名单,其中;> 作为第一个参数和拉姆达EX pression作为第二个参数

大多数我所看到的都是因为扩展方法或涉及LINQ的例子。我正在寻找一个纯老方法的例子。

解决方案

 公共无效每个< T>(IEnumerable的< T>的项目,行动< T>动作)
{
    的foreach(在项目VAR项)
        行动项目);
}
 

......正是如此称呼它:

 每个(myList上,I => Console.WriteLine(一));
 

First, I know there are methods off of the generic List<> class already in the framework do iterate over the List<>.

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.

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);
}

... and call it thusly:

Each(myList, i => Console.WriteLine(i));

这篇关于C#语法 - 的LAMBDA前pression例子 - 的ForEach()在泛型列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆