简单(我猜不到我)LINQ:我有一个数组列表,我希望得到一个包含每列平均值的集合。类似的东西:
var myCollection = new List<double[]>();
myCollection.Add(new []{1,2,3,4,5});
myCollection.Add(new []{3,4,5,6,7});
// Your answer --> {2,3,4,5,6}
答案 0 :(得分:1)
喜欢这样吗?
var myCollection = new List<double[]>();
myCollection.Add(new double[]{1,2,3,4,5});
myCollection.Add(new double[]{3,4,5,6,7});
var qry = (from col in Enumerable.Range(0, myCollection.Min(arr => arr.Length))
select myCollection.Average(arr => arr[col])).ToList();
当问题提到“二维数组”时的原始答案:
如何(注意 - 您可能需要撤消col
和row
,具体取决于您选择如何定位数据:
int[,] data = {{0,1,2},{3,4,5}};
var qry = (from col in Enumerable.Range(0, data.GetLength(0))
select new {
col, avg = Enumerable.Range(0, data.GetLength(1))
.Select(row => data[col, row]).Average()
}).ToList();
foreach(var result in qry) {
Console.WriteLine("{0}: {1}", result.col, result.avg);
}
或者如果你只想要平均值(不是anon-type):
var qry = (from col in Enumerable.Range(0, data.GetLength(0))
select Enumerable.Range(0, data.GetLength(1))
.Select(row => data[col, row]).Average()).ToList();
答案 1 :(得分:1)
由于您修改了问题,将二维数组更改为List<double[]>
,另一种解决方案是:
var result = myCollection.Aggregate((arr1, arr2) => arr1.Zip(arr2, (x, y) => (x + y) / 2).ToArray())