[英]How to sum List<int> values but only by cells in C#?
例如,我將其作為List<List<int>>
:
[2,4,4,2,5]
[1,3,6,3,8]
[0,3,9,0,0]
應該返回總和,但只取單元格,假設單元格計數始終相同:
[3, 10, 19, 5, 13]
如果可能的話,我正在嘗試使用Linq
找到一種簡單的方法來解決這個問題,因為我正在使用很多for
循環和if
條件來解決這個問題,而且我自己也很復雜。
有沒有可能使用 Linq 實現這一目標的方法?
Linq方法
List<List<int>> items = new List<List<int>>() {
new List<int> { 2, 4, 4, 2, 5 },
new List<int> { 1, 3, 6, 3, 8 },
new List<int> { 0, 3, 9, 0, 0 } };
List<int> result = Enumerable.Range(0, items.Min(x => x.Count)).Select(x => items.Sum(y => y[x])).ToList();
var xx = new List<List<int>>() {
new List<int>() { 2, 4, 4, 2, 5 },
new List<int>() { 1, 3, 6, 3, 8 },
new List<int>() { 0, 3, 9, 0, 0 },
};
var y = xx.Aggregate((r, x) => r.Zip(x).Select(p => p.First + p.Second).ToList());
我用很多
for
循環和if
條件來做這件事,我讓自己復雜化了。
您可以通過使用單個for
循環來完成它。
實現這一目標的兩種可能方法是:
方法一
0
s 填充數組方法二
兩種方法都受益於問題帖子中給出的假設:
[...] 假設細胞計數始終相同
如果您的原始列表集合被定義為List<List<int>>
:
List<List<int>> valuesCollection = new()
{
new() { 2, 4, 4, 2, 5 },
new() { 1, 3, 6, 3, 8 },
new() { 0, 3, 9, 0, 0 },
};
,這兩種方法可以實現如下:
方法一
var indexCount = valuesCollection[0].Count;
var sums = new int[indexCount];
Array.Fill(sums, 0);
foreach (var values in valuesCollection)
{
for (var i = 0; i < sums.Length; i++)
{
sums[i] += values[i];
}
}
方法二
System.Linq
var sums = valuesCollection[0].ToList();
foreach (var values in valuesCollection.Skip(1))
{
for (var i = 0; i < sums.Count; i++)
{
sums[i] += values[i];
}
}
使用任一方法, sums
的結果內容將為{ 3, 10, 19, 5, 13 }
。
示例小提琴在這里。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.