.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal

Home >> Code Snippets >> LINQ >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Using Average and Aggregate Function in LINQ

Posted By:Hefin Dsouza       Posted Date: August 12, 2009    Points: 10    Category: LINQ    URL: http://www.dotnetspark.com  

This will allow you to calculate the average of numbers in the given array.
It also has the way to calculate the average of charaters in the given string array.

Sub Main()
Dim marks() As Integer = {22, 44, 12, 55}
Dim avg = marks.Average()
Console.WriteLine("The Average of the Numbers are : " & avg)

Dim names() As String = {"HEFIN", "DOTNETSPIDER", "VISUAL STUDIO"}

Dim avgwordleng = names.Average(Function(m) m.Length)
Console.WriteLine("Average Length of words in the array are :" & avgwordleng)
End Sub

This Sample Allows you to use the aggregate function on arrays

Sub Main()
Dim numbers() As Integer = {10, 20, 33, 44, 33}

Dim sumAgg = numbers.Aggregate(Function(n, m) n + m)
Dim proAgg = numbers.Aggregate(Function(n, m) n * m)
Dim subAgg = numbers.Aggregate(Function(n, m) n - m)
Console.WriteLine("Sum Using Aggregate : " & sumAgg)
Console.WriteLine("Product Using Aggregate : " & proAgg)
Console.WriteLine("Subtraction Using Aggregate : " & subAgg)
'Similarly you can add any math's calculation to these arrays
'ArrayName.Aggregate(Function(a,b) a [operator] b)

End Sub

Remember to
Import System.Linq
*Note : This only works in Framework 3.5
Regards Hefin Dsouza


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend