每个索引的嵌套列表中的值求和 [英] Summing values across nested lists at each index

查看:116
本文介绍了每个索引的嵌套列表中的值求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为_DataCollection的List<List<string>>,其中每个嵌套列表都具有相等数量的值.尽管是所有字符串,但嵌套列表中的值将是由字母数字字符,空字符串或货币值组成的字符串.例如

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.

我能想到的唯一方法是遍历所有这些并保持连续运行,但是我想知道是否可以使用LINQ或其他方法来实现它.

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.

推荐答案

在这里.

var list = new List<List<string>>
{
    new List<string> {"tom", "abc", "$525.34", "$123"},
    new List<string> {"dick", "xyz", "$100", "$234"},
    new List<string> {"harry", "", "$250.01", "$40"},
    new List<string> {"bob", "", "$250.01", ""}
};

decimal num;
var itemsPerLine = list[0].Count; // 4
var res = list.SelectMany(line => line);
              .Select((s, i) => new { Text = s, Index = i })
              .GroupBy(i => i.Index % itemsPerLine) // transformed matrix here
              .Select(g => g.Sum(i => 
                   decimal.TryParse(i.Text, NumberStyles.AllowCurrencySymbol | 
                                            NumberStyles.AllowDecimalPoint, 
                                            new CultureInfo("en-US"), out num) 
                                            ? num : 0));

您当然可以通过更改NumberStyles标志和区域性信息来指定应识别为数字的数字.

You can, of course, specify what should be recognized as a number by changing NumberStyles flags and culture info.

这篇关于每个索引的嵌套列表中的值求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆