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

use*_*559 6 c# linq nested list

我有一个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", ""}
Run Code Online (Sandbox Code Playgroud)

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

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 "".
Run Code Online (Sandbox Code Playgroud)

基本上,每个索引的嵌套列表中的所有数值总和.

我能想到的唯一方法是迭代这些并保持运行总计,但我想知道我是否可以使用LINQ或其他东西来做.

Rah*_*ngh 9

试试这个:-

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));
Run Code Online (Sandbox Code Playgroud)

工作小提琴.


Ond*_*cek 4

干得好。

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));
Run Code Online (Sandbox Code Playgroud)

当然,您可以通过更改 NumberStyles 标志和区域性信息来指定应将哪些内容识别为数字。