Reputation: 9393
I have a double[] array holding many numbers.
I have an algorithm that selects sections from within this array that fall under certain conditions (value greater than x, at least y values, etc.)
Now I want to calculate the average value of all these values in my section.
So, say my section is from index 20 to 40. Now I have 20 values. Is there an easy way to do this in C# or do I have to loop over my array and calculate the average by hand?
Upvotes: 1
Views: 8897
Reputation: 27727
You can use the skip and take methods of linq to choose particular indexes:
var myData = new double[] { ..... };
var average = myList.Skip(20).Take(21).Average();
Upvotes: 0
Reputation: 241711
Use Enumerable.Average:
double[] values = new[] { 1.0, 2.0, 3.14, 2.71, 9.1 };
double average = values.Where(x => x > 2.0 && x < 4.0).Average();
Therefore, to use this with your selection methods you should consider having those methods return IEnumerable<double>
. So, as an example:
public IEnumerable<double> GreaterThan(double[] values, double value) {
for(int i = 0; i < values.Length; i++) {
if(values[i] > value) {
yield return values[i];
}
}
Then:
// values is double[]
double average = GreaterThan(values, 2.0).Average();
You can even make the above an extension method so that it reads nicely:
double average = values.GreaterThan(2.0).Average();
I would encourage you to write your filtering methods to return IEnumerable<double>
.
Upvotes: 0
Reputation: 700592
Note that if you have the numbers with index 20 to 40, you don't have 20 numbers, you have 21 numbers.
You can use the Range method to create an IEnumerable for the indexes, then you can use the Average method to get the average of the numbers:
double average = Enumerable.Range(20, 21).Select(i => numbers[i]).Average();
Upvotes: 1
Reputation: 144206
double avg = array
.Skip(startIndex)
.Take(endIndex - startIndex + 1)
.Average();
Upvotes: 0
Reputation: 12346
var values = new[] { 1, 2, 3, 4, 5, 6, 7, 8 };
var average = values.Skip(2).Take(5).Average();
Upvotes: 10
Reputation: 8129
Use Linq:
var myList = new double[] {1,2,3}
var avg = myList.Where(i => i > 1 && i < 2).Avg();
Upvotes: 2