问题描述
可能重复:
LINQ 等效于 foreach for IEnumerable<T>
ienumerable 的 linq 扩展方法非常方便......但如果您只想对枚举中的每个项目应用一些计算而不返回任何内容,那么它就没有那么有用了.所以我想知道我是否只是错过了正确的方法,或者它真的不存在,因为我宁愿使用内置版本(如果它可用的话)......但我还没有找到一个:-)
The linq extension methods for ienumerable are very handy ... but not that useful if all you want to do is apply some computation to each item in the enumeration without returning anything. So I was wondering if perhaps I was just missing the right method, or if it truly doesn't exist as I'd rather use a built-in version if it's available ... but I haven't found one :-)
我可以发誓在某个地方有一个 .ForEach 方法,但我还没有找到它.与此同时,我确实编写了自己的版本,以防它对其他人有用:
I could have sworn there was a .ForEach method somewhere, but I have yet to find it. In the meantime, I did write my own version in case it's useful for anyone else:
using System.Collections;
using System.Collections.Generic;
public delegate void Function<T>(T item);
public delegate void Function(object item);
public static class EnumerableExtensions
{
public static void For(this IEnumerable enumerable, Function func)
{
foreach (object item in enumerable)
{
func(item);
}
}
public static void For<T>(this IEnumerable<T> enumerable, Function<T> func)
{
foreach (T item in enumerable)
{
func(item);
}
}
}
用法是:
myEnumerable.For
推荐答案
解释原因:
LINQ 本质上是函数式的.用于查询数据并返回结果.LINQ 查询不应该改变应用程序的状态(有一些例外,如缓存).因为 foreach 不返回任何结果,所以除了您传递给它的内容之外,它没有很多不涉及更改某物状态的用途.如果你需要一个 Foreach() 扩展方法,很容易自己动手.
LINQ is functional in nature. It is used to query data and return results. A LINQ query shouldn't be altering the state of the application (with some exceptions like caching). Because foreach doesn't return any results, it doesn't have many uses that don't involve altering the state of something besides what you are passing in to it. And if you need a Foreach() extension method, it is easy to roll your own.
另一方面,如果您想要获取输入并在返回结果的每个项目上调用一个函数,则 LINQ 提供了一种通过其 select 方法的方法.
If, on the other hand, what you want is to take input and call a function on each item that returns a result, LINQ provides a way through its select method.
例如,以下代码对列表中的每个项目调用一个函数委托,如果该项目为正则返回 true:
For example, the following code calls a function delegate on every item in a list, returning true if that item is positive:
static void Main(string[] args)
{
IEnumerable<int> list = new List<int>() { -5, 3, -2, 1, 2, -7 };
IEnumerable<bool> isPositiveList = list.Select<int, bool>(i => i > 0);
foreach (bool isPositive in isPositiveList)
{
Console.WriteLine(isPositive);
}
Console.ReadKey();
}
这篇关于现有的类似于 Parallel.For 的 LINQ 扩展方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!