转换现有代码片段以使用 Array.ForEach
我们知道,如果您有:
var aa = new [] { 1, 2, 3, 4, 5 };
for (int i = 0; i < aa.length; ++i)
{
aa[i] = aa[i] + 1;
}
这确实是
var aa = new [] { 1, 2, 3, 4, 5 };
Arrary.ForEach(aa, a => a + 1);
但是,如果我有这个怎么办:
var aa = new [] { 1, 2, 3, 4, 5 };
var ab = new [] { 1, 2, 3, 4, 5 };
for (int i = 0; i < aa.length; ++i)
{
aa[i] = ab[i] + 1;
}
我可以将其转换为仅使用一个 Array.ForEach 吗? 或者,如果你想让所有函数式编程都变得疯狂,你会怎么做? 笨重的 for 循环看起来很丑。
We know that if you have:
var aa = new [] { 1, 2, 3, 4, 5 };
for (int i = 0; i < aa.length; ++i)
{
aa[i] = aa[i] + 1;
}
it's really
var aa = new [] { 1, 2, 3, 4, 5 };
Arrary.ForEach(aa, a => a + 1);
However, what if I had this:
var aa = new [] { 1, 2, 3, 4, 5 };
var ab = new [] { 1, 2, 3, 4, 5 };
for (int i = 0; i < aa.length; ++i)
{
aa[i] = ab[i] + 1;
}
Can I convert this to use just one Array.ForEach? Or, how would you do it, if you wanna go all functional programming crazy? Clunky for loops just looks ugly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
它并不漂亮,但它会起作用(使用返回元素索引的 Select() 重载):
恕我直言,在这种情况下,简单的“for”循环更容易理解。
It's not pretty, but this will work (using the Select() overload that returns the index of the element):
IMHO a simple "for" loops is a lot easier to understand in this case.
另一种类似的方法:
Another similar approach:
这不会很快,但它可能会起作用
不幸的是,这对于具有重复元素的数组不起作用。
This won't be fast, but it just might work
Unfortunately thiswill not work for an array with duplicate elements.
这行不通吗? 它的 1 Array.ForEach 的索引器位于 Array.ForEach 之外。
Would this not work? Its 1 Array.ForEach with the indexer held outside of the Array.ForEach.
不是直接答案,但您需要 ForEach2,它迭代两个序列/数组。 不幸的是,这不包含在 BCL 中,因此您必须添加它。
但是,如果您尝试在 C# 中执行函数式操作,那么无论如何您可能都会有一个辅助库,所以这没什么大不了的。
Not a direct answer, but you want ForEach2, which iterates over two sequences/arrays. Unfortunately this is not included with the BCL, so you'll have to add it.
But if you're trying to do functional in C#, you'll probably have a helper library anyways, so it's not that big of a deal.
怎么样:
How about: