find the average of a list of numbers in csharp

To find the average of a list of numbers in C#, you can use LINQ extension method Average(). Here's an example:

main.cs
List<int> numbers = new List<int> { 4, 5, 6, 7, 8 };
double average = numbers.Average();
Console.WriteLine("The average is: " + average);
138 chars
4 lines

In this example, we create a list of integers numbers containing 5 elements. We then call the Average() method on this list, which returns the average of all the elements. The result is stored in a double variable average, and printed to the console using Console.WriteLine().

If the list is empty, the Average() method will throw an exception. To avoid this, you can use AverageOrDefault() method instead, which will return 0 (or your chosen default value) for an empty list:

main.cs
List<int> numbers = new List<int>(); // an empty list
double average = numbers.AverageOrDefault();
Console.WriteLine("The average is: " + average);
148 chars
4 lines

gistlibby LogSnag