添加/总结两个数组 [英] Adding/summing two arrays

查看:185
本文介绍了添加/总结两个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到这感觉就像是有一个简单的解决方案,如果我找到合适的LINQ方法纯属假设的问题...

I've encountered a purely hypothetical problem which feels like it has an easy solution if I find the right linq method...

我有int的两个数组我知道他们是相同的大小。我想创建相同的大小被所述第三数组中的元素是在相应位置的第一两个数组中的元素的总和的第三阵列

I have two arrays of ints and I know they are the same size. I want to create a third array of the same size were the elements in the third array are the sum of the elements in the first two arrays in the corresponding position.

下面这是几乎可以肯定不会编译应该显示我想要做的方法。

Below is a method that almost certainly doesn't compile that should show what I want to do.

public static int[] AddArrays(int[] a, int[] b)
{
    int[] newArray;
    for (int i = 0; i<=a.Length; i++)
    {
        newArray[i]=a[i]+b[i];
    }
    return newArray;
}



有没有我可以使用像

Are there any Linq methods that I can just use like

return a.DoStuff(b, (x,y) => x+y)

或类似的东西?

我要指出,这很可能落在因为功课类别最初的问题,从一个网站,我一直在寻找(虽然我不能找到一个直接链接到这个问题),来到不作为的问题,我因工作需要或任何东西。

I should note that this probably falls in the category of homework since the original problem came from a website I was looking at (though I can't find a direct link to the problem) and not as a question I need for work or anything.

如果没有简单的方法存在,那么什么是最Linqy方式做到这一点?一个 array.each 似乎已经不能够索引第二个数组容易的值添加到您通过领先我,如果LINQ到怀疑迭代的人的问题会有什么帮助都在那种情况下...

If no simple method exists then what is the most Linqy way to do this? an array.each would seem to have the problem of not being able to index the second array easily to add the values to the one you are iterating through leading me to wonder if Linq would be any help at all in that situation...

推荐答案

邮编吧:)

var a = new int[] {1,2,3 };
var b = new int[] {4,5,6 };
a.Zip(b, (x, y) => x + y)

这篇关于添加/总结两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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