C# LINQ Enumerable.GroupBy Method in ASP.Net
The GroupBy method of System.Linq.Enumerable class enables to group the elements of a sequence. The overloaded functions of GroupBy method allows to pass the Group key value to the method according to which you want to group the elements of the sequence. You can also use the IEqualityComparer for the method that enables it to compare the elements using the specified comparer logic. The overloaded function of LINQ GroupBy method also allows to project the element of the grouped sequence into a new form. The GroupBy method has the following 8 types of overloaded functions which accept one or more parameters:
// 1. public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector); // 2. public static IEnumerable<TResult> GroupBy<TSource, TKey, TResult>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TKey, IEnumerable<TSource>, TResult> resultSelector); // 3. public static IEnumerable<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector); // 4. public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer); // 5. public static IEnumerable<TResult> GroupBy<TSource, TKey, TResult>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TKey, IEnumerable<TSource>, TResult> resultSelector, IEqualityComparer<TKey> comparer); // 6. public static IEnumerable<TResult> GroupBy<TSource, TKey, TElement, TResult>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, Func<TKey, IEnumerable<TElement>, TResult> resultSelector); // 7. public static IEnumerable<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer); // 8. public static IEnumerable<TResult> GroupBy<TSource, TKey, TElement, TResult>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, Func<TKey, IEnumerable<TElement>, TResult> resultSelector, IEqualityComparer<TKey> comparer);
C# LINQ GoupBy Method Example in ASP.Net
List<Employee> Employees = new List<Employee>()
{
new Employee(1, "Terry", "Adams", 27, 5),
new Employee(2, "Hugo", "Garcia", 27, 3),
new Employee(3, "Fadi", "Fakhouri", 30, 5),
new Employee(4, "Debra", "Garcia", 30, 4),
new Employee(5, "Lance", "Tucker", 35, 7),
new Employee(6, "Hanying", "Feng", 35, 5),
new Employee(7, "Michael", "Tucker", 28, 5),
new Employee(8, "Eugene", "Zabokritski", 37, 10),
new Employee(9, "Sven", "Mortensen", 37, 8),
new Employee(10, "Svetlana", "Omelchenko", 37, 7)
};
// first overloaded GroupBy method
IEnumerable<IGrouping<int, Employee>> employeesGroup1 = Employees.GroupBy(employee => employee.Age);
foreach (IGrouping<int, Employee> employeeGroup in employeesGroup1)
{
Response.Output.Write("{0}<br />", employeeGroup.Key);
foreach (Employee employee in employeeGroup)
{
Response.Output.Write("{0} {1}<br />", employee.FirstName, employee.LastName);
}
}
List<Product> products = new List<Product>()
{
new Product{ ProductName = "Butter", ProductID = 1 },
new Product{ ProductName = "Cheese", ProductID = 2 },
new Product{ ProductName = "Chocolate", ProductID = 3 },
};
// second overloaded GroupBy method
IEnumerable<IGrouping<char, Product>> productsQuery = products.GroupBy(product => product.ProductName[0], new ProductNameComparer());
foreach (IGrouping<char, Product> productGroup in productsQuery)
{
Response.Output.Write("{0}<br />", productGroup.Key);
foreach (Product product in productGroup)
{
Response.Output.Write("{0} {1}<br />", product.ProductName, product.ProductID);
}
}
// third overloaded GroupBy method
IEnumerable<IGrouping<int, string>> employeesGroup2 = Employees.GroupBy(employee => employee.Age, employee => employee.FirstName);
foreach (IGrouping<int, string> employeeGroup in employeesGroup2)
{
Response.Output.Write("{0}<br />", employeeGroup.Key);
foreach (string employeeFirstName in employeeGroup)
{
Response.Output.Write("{0}<br />", employeeFirstName);
}
}
// forth overloaded GroupBy method
var employeesGroup3 = Employees.GroupBy(employee => employee.Age, (age, employees) => new { Key = age, Count = employees.Count() });
foreach (var employeeGroup in employeesGroup3)
{
Response.Output.Write("{0} : {1}<br />", employeeGroup.Key, employeeGroup.Count);
}
// fifth overloaded GroupBy method
var employeesGroup4 = Employees.GroupBy(employee => employee.Age / 10, employee => employee.Age, (age, ages) => new { Key = age, Count = ages.Count(), Min = ages.Min(), Max = ages.Max() });
foreach (var employeeGroup in employeesGroup4)
{
Response.Output.Write("Age Group: {0} - {1}, Count: {2}, Min - Max: {3} - {4}<br />", employeeGroup.Key * 10, employeeGroup.Key * 10 + 10, employeeGroup.Count, employeeGroup.Min, employeeGroup.Max);
}
// Output:
// first output:
// 27
// Terry Adams
// Hugo Garcia
// 30
// Fadi Fakhouri
// Debra Garcia
// 35
// Lance Tucker
// Hanying Feng
// 28
// Michael Tucker
// 37
// Eugene Zabokritski
// Sven Mortensen
// Svetlana Omelchenko
// second output:
// B
// Butter 1
// C
// Cheese 2
// Chocolate 3
// third output:
// 27
// Terry
// Hugo
// 30
// Fadi
// Debra
// 35
// Lance
// Hanying
// 28
// Michael
// 37
// Eugene
// Sven
// Svetlana
// forth output:
// 27 : 2
// 30 : 2
// 35 : 2
// 28 : 1
// 37 : 3
// fifth output:
// Age Group: 20 - 30, Count: 3, Min - Max: 27 - 28
// Age Group: 30 - 40, Count: 7, Min - Max: 30 - 37
C# Product Class:
public class Product : IEquatable<Product>
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public bool Equals(Product other)
{
// check whether the compared object is null
if (Object.ReferenceEquals(other, null))
return false;
// check whether compared objects reference the same data
if (Object.ReferenceEquals(this, other)) return true;
// check whether the properties are equal
return this.ProductID == other.ProductID && this.ProductName == other.ProductName;
}
public override int GetHashCode()
{
// get hash code for product name
int productNameHashCode = this.ProductName == null ? 0 : this.ProductName.GetHashCode();
// get hash code for product id
int productIdHashCode = this.ProductID.GetHashCode();
// calculate the hash code for the object
return productIdHashCode ^ productIdHashCode;
}
}
public class ProductNameComparer : IEqualityComparer<char>
{
public bool Equals(char x, char y)
{
// check whether both the objects reference the same data
if (Object.ReferenceEquals(x, y)) return true;
// check whether any of the object is null
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
// check whether the properties are equal
return x == y;
}
public int GetHashCode(char obj)
{
// check whether the object is null
if (Object.ReferenceEquals(obj, null)) return 0;
// get hash code for the object
int HashCode = obj.GetHashCode();
// calculate the hash code for the object
return HashCode;
}
}
public class ProductComparer : IEqualityComparer<Product>
{
public bool Equals(Product x, Product y)
{
// check whether both the objects reference the same data
if (Object.ReferenceEquals(x, y)) return true;
// check whether any of the object is null
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
// check whether the properties are equal
return x.ProductID == y.ProductID && x.ProductName == y.ProductName;
}
public int GetHashCode(Product obj)
{
// check whether the object is null
if (Object.ReferenceEquals(obj, null)) return 0;
// get hash code for product name
int productNameHashCode = obj.ProductName == null ? 0 : obj.ProductName.GetHashCode();
// get hash code for product id
int productIdHashCode = obj.ProductID.GetHashCode();
// calculate the hash code for the object
return productIdHashCode ^ productIdHashCode;
}
}
C# Employee Class:
public class Employee
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public int Experience { get; set; }
public Employee(int Id, string firstName, string lastName, int age, int experience)
{
this.ID = Id;
this.FirstName = firstName;
this.LastName = lastName;
this.Age = age;
this.Experience = experience;
}
}
Continue to next tutorial: C# LINQ Enumerable.GroupJoin Method in ASP.Net to learn how to join and group the elements of two sequences.

* will not be published
* hint: http://www.example.com