问题描述
我有一个IEnumerable<IEnumerable<double>>
,它基本上可以看作是2D的双精度数组,而我想做的就是得到一个1D数组(或列表或其他东西),该数组是原始集合中所有列的总和.换句话说,如果我有:
I have an IEnumerable<IEnumerable<double>>
which can basically be thought of as a 2D array of doubles and what I want to do is get a 1D array (or list or whatever) that is the total for all the columns of my original collection. In other words, if I had:
1 2 3 4
2 3 1 6
3 4 5 6
-------------
6 9 9 16
我想要最后一行(显然,这不是原始集合的一部分).
I'd want the last line (which is not part of the original collection, obviously).
是否有使用LINQ做到这一点的简单方法,这样我就不必遍历整个事情了?我知道我可以使用.Sum
总计一行或一列,但是我想总计每一行.
Is there a simple way to do this with LINQ so that I don't have to loop over the whole thing? I know I can use .Sum
to total one row or one column, but I want to total each row.
我已经看到其他一些建议使用group
的问题(主要是处理数据库查询),但这似乎对我不起作用.我试过了:
I've seen some other questions (mostly dealing with database queries) that suggest using group
but that didn't seem to work for me. I tried this:
var totals = from p in toTotal
group p by 1 into g
select g.Sum(t => t.First());
但这只是全部内容.
有聪明的方法吗?
例如,如果toTotal
被定义为:
List<List<double>> toTotal = new List<List<double>>() {
new List<double> {1, 2, 3, 4},
new List<double> {2, 3 , 1, 6},
new List<double> {3 , 4, 5 , 6}
};
推荐答案
好.我想我已经做到了:
Ok. I think I've hit on it:
var totals = toTotal.Aggregate((prev, next) => prev.Zip(next, (a, b) => a + b));
诀窍是我正在寻找Fold
(或Reduce
)函数,但是在LINQ中它称为Aggregate
.
The trick was that I was looking for a Fold
(or Reduce
) function, but in LINQ it's called Aggregate
.
这是一个小提琴,其中显示了此代码以及@Habib的用于总计行的代码(以进行比较).与此处(以及我在实际代码中使用的内容)相比,唯一的变化是我需要对.Zip
的结果进行.ToList
,因为对于此测试用例,我有一个List<List<double>>
,这似乎使如果您未明确转换为列表,则为编译器.在我的实际代码中,toTotal
是IEnumerable<IEnumerable<double>>
,不需要转换.
Here's a fiddle showing this and @Habib's code for totaling rows (for comparison). The only change from what I have here (and what I was using in my actual code) is that I needed to .ToList
the result of .Zip
because for this test case I have a List<List<double>>
and that seems to upset the compiler if you don't explicitly convert to a list. In my actual code toTotal
is an IEnumerable<IEnumerable<double>>
and doesn't need converting.
这篇关于2D阵列的总和列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!