c# - LINQ 副作用

标签 c# linq foreach

是否可以用 LINQ 中的 lambda 表达式替换 foreach 循环 (.Select))?

List<int> l = {1, 2, 3, 4, 5};
foreach (int i in l)
    Console.WriteLine(i);

收件人:

List<int> l = {1, 2, 3, 4, 5};
l.Select(/* print to console */);

最佳答案

没有与 foreach 等效的 Linq,尽管您自己实现一个相当容易。

Eric Lippert 给出了很好的描述 here为什么这没有在 Linq 本身中实现。

但是,如果您的集合是一个列表(在您的示例中似乎是),您可以使用 List.ForEach :

myList.ForEach(item => Console.WriteLine(item));

关于c# - LINQ 副作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5632222/

相关文章:

c# - 我想从 GridView 中删除记录。在此之前要求确认,如 "Are you sure to delete?"

c# - 错误:类型为Image <TColor,TDepth >' exists in both ' Emgu.CV.World,版本= 3.3.0.2824和Emgu.CV,版本= 2.2.1.1150

c# - TableView 单元格在滚动时重置其数据

c# - 如何对 SQLite 数据库进行 LINQ 查询?

asp.net-mvc-3 - 将自定义方法集成到 LINQ to Entities 查询中

javascript - 离开拥抱方法如何从forEach返回?

c# - 每个 IP 一键点击

c# - 如何将其建模为 LINQ 查询?

c++ - 使用 boost::fusion::for_each 时传递/绑定(bind)参数

javascript - 使用 fetch 和 forEach 对动态 HTML 进行事件绑定(bind)