LINQ Average Function to Get Average of Items in List

  Total Views : 310
  Comments : 0
 
  Keywords : How to use linq average() function to get the average of items in list with example, Find the average of items of in list with example, Linq use average method to calculate average from list

Here we will learn linq average() function / operator in c#, vb.net with example and how to use linq average() function to get average of items in list with example in c#, vb.net.

LINQ Average() Function

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

Syntax of LINQ Average() Function

Following is the syntax of using linq average() function to get the average of elements in the list.

 

C# Code

 

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

double Average = Num.Average();

VB.NET Code

 

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

Dim Average As Double = Num.Average()

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

LINQ Average() Function Example 

Now we will see the example of using LINQ Average() function to calculate average of items in collection / list.

 

C# Code

 

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();

}

}

}

VB.NET Code

 

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 above example we used Average() function to get the average of all the elements from the collection. Now we will run and see the output of above example.

Output of LINQ Average() Function

Following is the result of using LINQ Average() function to get the average of items in array list.

 

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.

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User