LINQ Average Function to Get Average of Items in List

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

 

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

Syntax of LINQ Average() Function C#

int[] Num = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

double Average = Num.Average();

LINQ Average() Function Syntax 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 are getting the average of the items in "Num" list using LINQ Average() function.

 

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

 

LINQ Average() Function Example 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 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 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 like as shown below.

 

Find the average of the elements:

 

The Average is 5

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