Aggregation Operator: Average
Average extension method calculates the average of the numeric items in the collection. Average method returns nullable or non-nullable decimal, double or float value.
The following example demonstrate Agerage method that returns average value of all the integers in the collection.
IList<int> intList = new List<int>>() { 10, 20, 30 };
var avg = intList.Average();
Console.WriteLine("Average: {0}", avg);
You can specify an int, decimal, double or float property of a class as a lambda expression of which you want to get an average value. The following example demonstrates Average method on the complex type.
IList<Student> studentList = new List<Student>>() {
new Student() { StudentID = 1, StudentName = "John", Age = 13} ,
new Student() { StudentID = 2, StudentName = "Moin", Age = 21 } ,
new Student() { StudentID = 3, StudentName = "Bill", Age = 18 } ,
new Student() { StudentID = 4, StudentName = "Ram" , Age = 20} ,
new Student() { StudentID = 5, StudentName = "Ron" , Age = 15 }
};
var avgAge = studentList.Average(s => s.Age);
Console.WriteLine("Average Age of Student: {0}", avgAge);
The Average operator in query syntax is Not Supported in C#. However, it is supported in VB.Net
Learn about another aggregate operator - Count.
Aggregation Operator: Count
The Count operator returns the number of elements in the collection or number of elements that have satisfied the given condition.
The Count() extension method has the following two overloads:
int Count<TSource>();int Count<TSource>(Func<TSource, bool> predicate);
The first overload method of Count returns the number of elements in the specified collection, whereas the second overload method returns the number of elements which have satisfied the specified condition given as lambda expression/predicate function.
The following example demonstrates Count() on primitive collection.
IList<int> intList = new List<int>() { 10, 21, 30, 45, 50 };
var totalElements = intList.Count();
Console.WriteLine("Total Elements: {0}", totalElements);
var evenElements = intList.Count(i => i%2 == 0);
Console.WriteLine("Even Elements: {0}", evenElements);
Even Elements: 3
The following example demonstrates Count() method on the complex type collection.
IList<Student> studentList = new List<Student>>() {
new Student() { StudentID = 1, StudentName = "John", Age = 13} ,
new Student() { StudentID = 2, StudentName = "Moin", Age = 21 } ,
new Student() { StudentID = 3, StudentName = "Bill", Age = 18 } ,
new Student() { StudentID = 4, StudentName = "Ram" , Age = 20} ,
new Student() { StudentID = 5, StudentName = "Mathew" , Age = 15 }
};
var totalStudents = studentList.Count();
Console.WriteLine("Total Students: {0}", totalStudents);
var adultStudents = studentList.Count(s => s.Age >= 18);
Console.WriteLine("Number of Adult Students: {0}", adultStudents );
Number of Adult Students: 3
Dim studentList = New List(Of Student) From {
New Student() With {.StudentID = 1, .StudentName = "John", .Age = 13},
New Student() With {.StudentID = 2, .StudentName = "Moin", .Age = 21},
New Student() With {.StudentID = 3, .StudentName = "Bill", .Age = 18},
New Student() With {.StudentID = 4, .StudentName = "Ram", .Age = 20},
New Student() With {.StudentID = 5, .StudentName = "Ron", .Age = 15}
}
Dim totalStudents = studentList.Count()
Console.WriteLine("Total Students: {0}", totalStudents)
Count(predicate) extension method with predicate parameter is Not Supported in VB.Net.
Count Operator in Query Syntax
// Student collection
Dim studentList = New List(Of Student) From {
New Student() With {.StudentID = 1, .StudentName = "John", .Age = 13},
New Student() With {.StudentID = 2, .StudentName = "Moin", .Age = 21},
New Student() With {.StudentID = 3, .StudentName = "Bill", .Age = 18},
New Student() With {.StudentID = 4, .StudentName = "Ram", .Age = 20},
New Student() With {.StudentID = 5, .StudentName = "Ron", .Age = 15}
}
Dim totalStudents = Aggregate st In studentList
Into Count(st.Age >= 18)
Console.WriteLine("Total Students: {0}", totalStudents)
C# Query Syntax doesn't support aggregation operators. However, you can wrap the query into brackets and use an aggregation functions as shown below.
var totalAge = (from s in studentList
select s.age).Count();
Learn about another aggregate operator - Max .
Aggregation Operator: Max
The Max() method returns the largest numeric element from a collection.
The following example demonstrates Max() on primitive collection.
IList<int> intList = new List<int>() { 10, 21, 30, 45, 50, 87 };
var largest = intList.Max();
Console.WriteLine("Largest Element: {0}", largest);
var largestEvenElements = intList.Max(i => {
if(i%2 == 0)
return i;
return 0;
});
Console.WriteLine("Largest Even Element: {0}", largestEvenElements );
Largest Even Element: 50
The following example demonstrates Max() method on the complex type collection.
IList<Student> studentList = new List<Student>>() {
new Student() { StudentID = 1, StudentName = "John", Age = 13} ,
new Student() { StudentID = 2, StudentName = "Moin", Age = 21 } ,
new Student() { StudentID = 3, StudentName = "Bill", Age = 18 } ,
new Student() { StudentID = 4, StudentName = "Ram" , Age = 20} ,
new Student() { StudentID = 5, StudentName = "Ron" , Age = 15 }
};
var oldest = studentList.Max(s => s.Age);
Console.WriteLine("Oldest Student Age: {0}", oldest);
Dim studentList = New List(Of Student) From {
New Student() With {.StudentID = 1, .StudentName = "John", .Age = 13},
New Student() With {.StudentID = 2, .StudentName = "Moin", .Age = 21},
New Student() With {.StudentID = 3, .StudentName = "Bill", .Age = 18},
New Student() With {.StudentID = 4, .StudentName = "Ram", .Age = 20},
New Student() With {.StudentID = 5, .StudentName = "Ron", .Age = 15}
}
Dim oldest = studentList.Max(Function(s) s.Age)
Console.WriteLine("Oldest Student Age: {0}", oldest)
Max returns a result of any data type. The following example shows how you can find a student with the longest name in the collection:
public class Student : IComparable<Student>
{
public int StudentID { get; set; }
public string StudentName { get; set; }
public int Age { get; set; }
public int StandardID { get; set; }
public int CompareTo(Student other)
{
if (this.StudentName.Length >= other.StudentName.Length)
return 1;
return 0;
}
}
class Program
{
static void Main(string[] args)
{
// Student collection
IList<Student> studentList = new List<Student>>() {
new Student() { StudentID = 1, StudentName = "John", Age = 13} ,
new Student() { StudentID = 2, StudentName = "Moin", Age = 21 } ,
new Student() { StudentID = 3, StudentName = "Bill", Age = 18 } ,
new Student() { StudentID = 4, StudentName = "Ram" , Age = 20} ,
new Student() { StudentID = 5, StudentName = "Steve" , Age = 15 }
};
var studentWithLongName = studentList.Max();
Console.WriteLine("Student ID: {0}, Student Name: {1}",
.StudentID, studentWithLongName.StudentName)
}
}
You can use Min extension method/operator the same way as Max.
As per the above example, to find the student with the longest name, you need to implement IComparable<T> interface and compare student names' length in CompareTo method. So now, you can use Max() method which will use CompareTo method in order to return appropriate result.
Max Operator in Query Syntax
Max operator is Not Supported in C# Query syntax. However, it is supported in VB.Net query syntax as shown below.
Dim studentList = New List(Of Student) From {
New Student() With {.StudentID = 1, .StudentName = "John", .Age = 13},
New Student() With {.StudentID = 2, .StudentName = "Moin", .Age = 21},
New Student() With {.StudentID = 3, .StudentName = "Bill", .Age = 18},
New Student() With {.StudentID = 4, .StudentName = "Ram", .Age = 20},
New Student() With {.StudentID = 5, .StudentName = "Ron", .Age = 15}
}
Dim maxAge = Aggregate st In studentList Into Max(st.Age)
Console.WriteLine("Maximum Age of Student: {0}", maxAge);
Learn about another aggregate operator - Sum.
Aggregation Operator: Sum
The Sum() method calculates the sum of numeric items in the collection.
The following example demonstrates Sum() on primitive collection.
IList<int> intList = new List<int>() { 10, 21, 30, 45, 50, 87 };
var total = intList.Sum();
Console.WriteLine("Sum: {0}", total);
var sumOfEvenElements = intList.Sum(i => {
if(i%2 == 0)
return i;
return 0;
});
Console.WriteLine("Sum of Even Elements: {0}", sumOfEvenElements );
Sum of Even Elements: 90
The following example calculates sum of all student's age and also number of adult students in a student collection.
IList<Student> studentList = new List<Student>>() {
new Student() { StudentID = 1, StudentName = "John", Age = 13} ,
new Student() { StudentID = 2, StudentName = "Moin", Age = 21 } ,
new Student() { StudentID = 3, StudentName = "Bill", Age = 18 } ,
new Student() { StudentID = 4, StudentName = "Ram" , Age = 20} ,
new Student() { StudentID = 5, StudentName = "Ron" , Age = 15 }
};
var sumOfAge = studentList.Sum(s => s.Age);
Console.WriteLine("Sum of all student's age: {0}", sumOfAge);
var numOfAdults = studentList.Sum(s => {
if(s.Age >= 18)
return 1;
else
return 0;
});
Console.WriteLine("Total Adult Students: {0}", numOfAdults);
// Student collection
Dim studentList = New List(Of Student) From {
New Student() With {.StudentID = 1, .StudentName = "John", .Age = 13},
New Student() With {.StudentID = 2, .StudentName = "Moin", .Age = 21},
New Student() With {.StudentID = 3, .StudentName = "Bill", .Age = 18},
New Student() With {.StudentID = 4, .StudentName = "Ram", .Age = 20},
New Student() With {.StudentID = 5, .StudentName = "Ron", .Age = 15}
}
Dim sumOfAge = studentList.Sum(Function(s) s.Age)
Console.WriteLine("Total Age of Student: {0}", sumOfAge)
Dim numOfAdults = studentList.Sum(Function(s)
if(s.Age >= 18)
return 1
else
return 0
end if
end function)
Console.WriteLine("Total Adult Students: {0}", numOfAdults)
Total Adult Students: 3
Sum operator in query syntax
Sum operator is Not Supported in C# Query syntax.
// Student collection
Dim studentList = New List(Of Student) From {
New Student() With {.StudentID = 1, .StudentName = "John", .Age = 13},
New Student() With {.StudentID = 2, .StudentName = "Moin", .Age = 21},
New Student() With {.StudentID = 3, .StudentName = "Bill", .Age = 18},
New Student() With {.StudentID = 4, .StudentName = "Ram", .Age = 20},
New Student() With {.StudentID = 5, .StudentName = "Ron", .Age = 15}
}
Dim totalAge = Aggregate st In studentList Into Sum(st.Age)
Console.WriteLine("Sum of all student's age: {0}", totalAge);