How do I sum a list<> of arrays

后端 未结 7 1392
故里飘歌
故里飘歌 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:10

    Here is one that trades the Linq statement simplicity with performance.

    var colSums = 
       from col in array.Pivot()
       select col.Sum();
    

     public static class LinqExtensions {
        public static IEnumerable<IEnumerable<T>> Pivot<T>( this IList<T[]> array ) {
            for( int c = 0; c < array[ 0 ].Length; c++ )
                yield return PivotColumn( array, c );
        }
        private static IEnumerable<T> PivotColumn<T>( IList<T[]> array, int c ) {
            for( int r = 0; r < array.Count; r++ )
                yield return array[ r ][ c ];
        }
    }
    
    0 讨论(0)
提交回复
热议问题