LINQ Average Function to Get Average of Items in List

In LINQ, the Average() function is useful to calculate the average of the elements present in the array.

 

Following is the syntax of using the LINQ average() function in c# and vb.net to get the average of the elements in the array list.

Syntax of LINQ Average() Function in C#

int[] Num = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
double Average = Num.Average();

LINQ Average() Function Syntax in VB.NET

 

Dim Num As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9}
Dim Average As Double = Num.Average()

If you observe the above syntax, we get the average of the items in the "Num" list using the LINQ Average() function.

 

Now, we will see the examples of using the LINQ Average() function in c# and vb.net to calculate the average of the items in the array list.

 

LINQ Average() Function Example in C#

using System;
using System.Collections.Generic;
using System.Linq;

namespace Linqtutorials
{
  class Program
  {
    static void Main(string[] args)
    {
      int[] Num = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
      Console.WriteLine("Find the average of the elements:");
      double Average = Num.Average();
      Console.WriteLine("The Average is {0}", Average);
      Console.ReadLine();
    }
  }
}

LINQ Average() Function Example in VB.NET 

Module Module1
Sub Main()
Dim Num As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9}
Console.WriteLine("Find the average of the elements:")
Dim Average As Double = Num.Average()
Console.WriteLine("The Average is {0}", Average)
Console.ReadLine()
End Sub
End Module

In the above example, we used the Average() function to get the average of the elements in the array list.

 

When we execute the above LINQ Average() function examples, we will get the result as shown below.

 

Find the average of the elements:

The Average is 5

This is how we can use LINQ Average() function to calculate the average of items in the list or collection object.