Sum-Up Values at Same Index in Nested List

This article attempts to explain how to sum up all the values present at the same index in a Nested List of integers.

While learning LINQ I realized that the only way to master LINQ is to practice many code snippets and examples. So, while doing that I came across a problem that I am sharing here.

Suppose we have a List of a List of Integers as follows (each list contains the same number of elements):

  1. List<List<int>> numbers = new List<List<int>>  
  2.             {  
  3.                 new List<int> { 23, 45, 12, 56 },  
  4.                 new List<int> { 78, 11, 7, 98 },  
  5.                 new List<int> { 5, 23, 55, 29 },  
  6.                 new List<int> { 17, 0, 3, 67 }  
  7.             }; 

Now, we want to sum up all the values present at the same index in each list, for example: Sum –> 23,78,5,17 from index 0 in each list and Sum –> 45,11,23,0 from index 1 and so on.

So my final output should be: 123, 79, 77, 250.

This can be easily done using loops, but let's explore how to do this using LINQ.

Logic

1. First break the nested list into a single list of integers, this can be easily done using SelectMany extension method.

  1. numbers.SelectMany(x => x) 

 

Please note we have all the items with their respective index.

2. Please note in the preceding figure, we need to add 23 (present at index 0), 78 (index 4), 5 (index 8) and 17 (index 12). So what's common between these index(es)? Yes, they are a multiple of 4 and why I am saying 4? That is the length of each list that we can easily identify using:
  1. int ListLength = numbers.First().Count; //4 

Now, select the values and index based on this ListLength.

  1. .Select((v, i) => new { Value = v, Index = i % ListLength }) 

 

Please note, now we have all the values attached with the same index value.

3. Now, all that is left is to group this collection based on its Index and sum-up its values:
  1. int ListLength = numbers.First().Count;  
  2. var query = numbers.SelectMany(x => x)  
  3.                    .Select((v, i) => new { Value = v, Index = i % ListLength })  
  4.                    .GroupBy(x => x.Index)  
  5.                    .Select(y => y.Sum(z => z.Value)); 

Please let me know if you have any questions.

Happy Coding.

Up Next
    Ebook Download
    View all
    Learn
    View all