In this article, We will learn The Linq Average method.
The Linq Average method is used to calculate the average of numeric values from the collection on which it is applied.
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp17 { class Program { static void Main(string[] args) { int[] intNumbers = new int[] { 60, 80, 50, 90, 10, 30, 70, 40, 20, 100 }; //Using Method Syntax var MSAverageValue = intNumbers.Average(); //Using Query Syntax var QSAverageValue = (from num in intNumbers select num).Average(); Console.WriteLine("Average Value = " + MSAverageValue); Console.ReadKey(); } } } |
Example2: Linq Average Method with filter
Now we need to return the average value from the collection where the number is greater than 50.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using System; using System.Linq; namespace LINQDemo { class Program { static void Main(string[] args) { int[] intNumbers = new int[] { 60, 80, 50, 90, 10, 30, 70, 40, 20, 100 }; //Using Method Syntax var MSAverageValue = intNumbers.Where(num => num > 50).Average(); //Using Query Syntax var QSAverageValue = (from num in intNumbers where num > 50 select num).Average(); Console.WriteLine("Average Value = " + MSAverageValue); Console.ReadKey(); } } } |