Skip to content

Instantly share code, notes, and snippets.

@Plus1XP
Created April 13, 2019 17:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Plus1XP/fb73f12ad09fc9fbafa2fddba6fc3e8b to your computer and use it in GitHub Desktop.
Save Plus1XP/fb73f12ad09fc9fbafa2fddba6fc3e8b to your computer and use it in GitHub Desktop.
Calculate the average value using a foreach loop vs. a LINQ function.
public void CalculateAverage()
{
// Create and populate the list of numbers
List<double> values = new List<double>();
values.Add(1);
values.Add(5);
values.Add(21);
// Calculating the average, using a foreach
double total = 0;
double counter = 0;
foreach(double value in values)
{
total = (total + value);
counter = (counter + 1);
}
double average = (total / counter);
// Calculating the average, using LINQ
double linqAverage = values.Average();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment