用于 IEnumerable<T> 的 foreach 的 LINQ 等价物 [英] LINQ equivalent of foreach for IEnumerable<T>

查看:34
本文介绍了用于 IEnumerable<T> 的 foreach 的 LINQ 等价物的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 LINQ 中执行以下等效操作,但我不知道如何:

I'd like to do the equivalent of the following in LINQ, but I can't figure out how:

IEnumerable<Item> items = GetItems();
items.ForEach(i => i.DoStuff());

真正的语法是什么?

推荐答案

IEnumerable 没有 ForEach 扩展;仅用于 List.所以你可以这样做

There is no ForEach extension for IEnumerable; only for List<T>. So you could do

items.ToList().ForEach(i => i.DoStuff());

或者,编写您自己的 ForEach 扩展方法:

Alternatively, write your own ForEach extension method:

public static void ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)
{
    foreach(T item in enumeration)
    {
        action(item);
    }
}

这篇关于用于 IEnumerable&lt;T&gt; 的 foreach 的 LINQ 等价物的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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