# How to use LINQ Aggregate operators in ASP.NET

April 27, 2014 0 Comments

### Introduction

The Aggregate operators compute a single value from a collection. The different Aggregate operators are: Aggregate, Average, Count, LongCount, Max, Min, and Sum. The Aggregate clause calculates a sum value of the values in the collection. The Average clause calculates the average value of the collection of the values. The Count clause counts the elements in the collection. The LongCount clause counts the elements in a large collection. The Max clause determines the maximum value in a collection. The Min clause determines the minimum value of the collection. The Sum clause calculates the sum of values in the collection.
The syntax of the Count clause is:
For C#
public static int Count<T>( this IEnumerable<T> source, Function<T, bool> predicate);
The Count clause throws an ArgumentNullException exception, if any argument is null and an OverflowException exception is thrown if the count exceeds the maximum value.
The syntax of the Sum clause is:
For C#
public static Numeric Sum<T>( this IEnumerable<T> source, Function<T, Numeric> selector);

The Sum clause returns 0 for an empty sequence. The clause does not include null values in its result.
The Aggregate clause applies a function over a sequence.
The syntax of the Aggregate clause is:
For C#
public static T Aggregate<T>( this IEnumerable<T> source, Function<T, T, T> func);
The LongCount clause counts the number of elements in the given sequence.
The syntax of the LongCount clause is:
For C#
public static lonq LonqCount<T>( this IEnumerable<T> source);
The Min clause finds the minimum value of the given sequence.
The syntax of the Min clause is:
For C#
public static T Min<T>(this IEnumerable<T> source);
The Max clause returns the maximum value of the given sequence.
The syntax of the Max clause is:
For C#
public static T Max<T>(this IEnumerable<T> source);

The Average clause computes the average of the given sequence.
The syntax of the Average clause is:
For C#
public static Result Average(this IEnumerable<Numeric> source);

### Lets take an simple example

<form id="form1" runat="server">
<div>

<asp:ListBox ID="ListBox1" runat="server" Height="176px" Width="267px">
</asp:ListBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Agg. Operator Ex" Width="107px" />

</div>
</form>
Code Behind
protected void Button1_Click(object sender, EventArgs e)
{
int[] num = { 5, 4, 3, 2, 1, 7, 8, 9, 10, 34, 67 };
double sum = num.Sum();
ListBox1.Items.Add("The Sum of the Number is= " + sum);
int minimum = num.Min();
ListBox1.Items.Add("Minimum Number is= " + minimum);
int oddnum = num.Count(n => n % 2 == 1);
ListBox1.Items.Add("Count of the odd Number is= " + oddnum);

}
Code Generate the following output

Some say he’s half man half fish, others say he’s more of a seventy/thirty split. Either way he’s a fishy bastard. Google