Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Summing values across nested lists at each index

Tags:

c#

list

linq

nested

I have a List<List<string>> called _DataCollection where each of the nested lists have an equal number of values. Although all strings, the values in the nested lists will be strings consisting of alphanumeric characters, empty strings, or a currency value. For example

_DataCollection[0] = {"tom", "abc", "$525.34", "$123"}
_DataCollection[1] = {"dick", "xyz", "$100", "$234"}
_DataCollection[2] = {"harry", "", "$250.01", "$40"}
_DataCollection[2] = {"bob", "", "$250.01", ""}

What I need to do is come up with a way to sum all values per index across all the nested lists and add this to a list:

newSumList[0] = "N/A" since "tom" + "dick" + "harry" + "bob" can't be aggregated.
newSumList[1] = "N/A" since "abc" + "xyz" + "" + "" can't be aggregated.
newSumList[2] = "1125.36"
newSumList[3] = "397" even though the last value of the last nested list is "".

Basically, total all numeric values in nested lists for each index.

The only way I can think of is to iterate though these and keep a running total, but I was wondering if I can do it using LINQ or something else.

like image 622
Palps Avatar asked Oct 27 '14 05:10

Palps


1 Answers

Try this:-

decimal _temp =0;
int ListLength = _DataCollection.First().Count();
            var query = _DataCollection.SelectMany(x => x).
                                       Select((v, i) => new { Val = v, Index = i % ListLength })
                                       .GroupBy(x => x.Index)
                                       .Select(z => z.Sum(y => decimal.TryParse(y.Val,out _temp) ? _temp : 0));

Working Fiddle.

like image 125
Rahul Singh Avatar answered Oct 13 '22 00:10

Rahul Singh