GibboK
GibboK

Reputation: 73908

Alternative to Linq Average method in C#

I would like to know an alternative way to write this code without using a Linq Method Average().

   double[] array1 = { 1, 2, 3, 5, 0 };
        double average1 = array1.Average();
        Console.WriteLine(average1);

Upvotes: 0

Views: 657

Answers (3)

Peter Ritchie
Peter Ritchie

Reputation: 35881

The question kind of vague, but some alternatives:

double average2 = array1.Sum() / Array.Length;

or

double sum = 0;
foreach(var item in array1)
{
   sum += item;
}
double average2 = sum / array1.Length;

Upvotes: 4

GregRos
GregRos

Reputation: 9103

To give you a concise answer that doesn't involve any LINQ methods (though why you'd restrict yourself to this, beats me):

double[] arr = new[] {1.0, 2.0, 3.0};
double avg = 0;
Array.ForEach(arr, x => avg += x)
avg = avg / arr.Length;

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

No idea why you wouldn't want to use the LINQ Average function but you could loop through the elements of the array in order to calculate the sum and finally divide by the number of elements:

double[] array1 = { 1, 2, 3, 5, 0 };
double average1 = 0;
foreach (var item in array1)
{
    average1 += item;
}
average1 = average1 / array1.Length;
Console.WriteLine(average1);

Now that you look at this code it is clear why the following is much better:

double[] array1 = { 1, 2, 3, 5, 0 };
double average1 = array1.Average();
Console.WriteLine(average1);

Upvotes: 2

Related Questions