本文介绍了如何汇总列表<>数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表< int []> myList,在这里我知道所有int []数组的长度都是相同的-为了便于讨论,让我们说我有500个数组,每个数组的长度为2048个元素.我想对所有500个数组求和,给我一个长2048个元素的数组,其中每个元素是所有其他数组中所有相同位置的总和.

I have a List< int[] > myList, where I know that all the int[] arrays are the same length - for the sake of argument, let us say I have 500 arrays, each is 2048 elements long. I'd like to sum all 500 of these arrays, to give me a single array, 2048 elements long, where each element is the sum of all the same positions in all the other arrays.

显然,这在命令式代码中是微不足道的:

Obviously this is trivial in imperative code:

int[] sums = new int[myList[0].Length];
foreach(int[] array in myList)
{
    for(int i = 0; i < sums.Length; i++)
    {
        sums[i] += array[i];
    }
}

但是我想知道是否有很好的Linq或Enumerable.xxx技术?

But I was wondering if there was a nice Linq or Enumerable.xxx technique?

推荐答案

哎呀...在我不看的时候,这变得有点困难.不断变化的需求可能是真正的PITA.

Ouch...This became a bit harder while I wasn't looking. Changing requirements can be a real PITA.

好的,所以取数组中的每个位置,然后求和:

Okay, so take each position in the array, and sum it:

var sums = Enumerable.Range(0, myList[0].Length)
           .Select(i => myList.Select(
                     nums => nums[i]
                  ).Sum()
           );

这有点丑陋...但是我认为声明版本会更糟.

That's kind of ugly...but I think the statement version would be even worse.

这篇关于如何汇总列表&lt;&gt;数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 13:35