Simple (not for me yet I guess) LINQ: I have a List of arrays, and I want to get a collection c开发者_如何学运维ontaining the average of each column. Something like:
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}
Like so?
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();
Original answer from when the question referred to a "2 dimensional array":
How about (note - you may need to reverse col
and row
depending on how you choose to orient your data):
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);
}
Or if you just want the averages (not the 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();
Since you have modified the question, changing the 2 dimensional array to List<double[]>
, another solution is:
var result = myCollection.Aggregate((arr1, arr2) => arr1.Zip(arr2, (x, y) => (x + y) / 2).ToArray())
精彩评论