How do I sum a list<> of arrays

后端 未结 7 1403
故里飘歌
故里飘歌 2021-02-04 08:24

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

7条回答
  •  失恋的感觉
    2021-02-04 09:04

    This works with any 2 sequences, not just arrays:

    var myList = new List
    {
        new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 },
        new int[] { 10, 20, 30, 40, 50, 60, 70, 80, 90 }
    };
    
    var sums =
        from array in myList
        from valueIndex in array.Select((value, index) => new { Value = value, Index = index })
        group valueIndex by valueIndex.Index into indexGroups
        select indexGroups.Select(indexGroup => indexGroup.Value).Sum()
    
    foreach(var sum in sums)
    {
        Console.WriteLine(sum);
    }
    
    // Prints:
    //
    // 11
    // 22
    // 33
    // 44
    // 55
    // 66
    // 77
    // 88
    // 99
    

提交回复
热议问题