gpt4 book ai didi

c# - 在每个索引处对嵌套列表中的值求和

转载 作者:太空狗 更新时间:2023-10-29 20:50:08 25 4
gpt4 key购买 nike

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

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

我需要做的是想出一种方法来对所有嵌套列表中每个索引的所有值求和并将其添加到列表中:

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 "".

基本上,对每个索引的嵌套列表中的所有数值进行总计。

我能想到的唯一方法是遍历这些并保持总计,但我想知道我是否可以使用 LINQ 或其他东西来做到这一点。

最佳答案

试试这个:-

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));

工作 Fiddle .

关于c# - 在每个索引处对嵌套列表中的值求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26581670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com