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):
- List<List<int>> numbers = new List<List<int>>
- {
- new List<int> { 23, 45, 12, 56 },
- new List<int> { 78, 11, 7, 98 },
- new List<int> { 5, 23, 55, 29 },
- new List<int> { 17, 0, 3, 67 }
- };
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.
- numbers.SelectMany(x => x)
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:
- int ListLength = numbers.First().Count; //4
Now, select the values and index based on this ListLength.
- .Select((v, i) => new { Value = v, Index = i % ListLength })
3. Now, all that is left is to group this collection based on its Index and sum-up its values:
- int ListLength = numbers.First().Count;
- var query = numbers.SelectMany(x => x)
- .Select((v, i) => new { Value = v, Index = i % ListLength })
- .GroupBy(x => x.Index)
- .Select(y => y.Sum(z => z.Value));
Please let me know if you have any questions.
Happy Coding.

Gowtham RajamanickamPosted Apr 11, 2015, 1:21 PM
good one