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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With