C# Enumerable GroupBy(IEnumerable, Func, Func, TResult>)

Description

Groups the elements of a sequence according to a specified key selector function and creates a result value from each group and its key.

Syntax


public static IEnumerable<TResult> GroupBy<TSource, TKey, TResult>(
  this IEnumerable<TSource> source,
  Func<TSource, TKey> keySelector,
  Func<TKey, IEnumerable<TSource>, TResult> resultSelector
)/* w ww  . java 2s  . c o  m*/

Parameters

  • TSource - The type of the elements of source.
  • TKey - The type of the key returned by keySelector.
  • TResult - The type of the result value returned by resultSelector.
  • source - An IEnumerable whose elements to group.
  • keySelector - A function to extract the key for each element.
  • resultSelector - A function to create a result value from each group.

Example

The following code example demonstrates how to use GroupBy to group the elements of a sequence and project a sequence of results of type TResult.


/* w  ww  .ja v  a2 s. c o m*/
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
  public static void Main(String[] argv){  
      List<Pet> petsList =new List<Pet>{ new Pet { Name="A", Age=8.3 },
                         new Pet { Name="B", Age=4.9 },
                         new Pet { Name="C", Age=1.5 },
                         new Pet { Name="D", Age=4.3 } };
      var query = petsList.GroupBy(
          pet => Math.Floor(pet.Age),
          (age, pets) => new
          {
              Key = age,
              Count = pets.Count(),
              Min = pets.Min(pet => pet.Age),
              Max = pets.Max(pet => pet.Age)
          });

      foreach (var result in query)
      {
          Console.WriteLine("\nAge group: " + result.Key);
          Console.WriteLine("Number of pets in this age group: " + result.Count);
          Console.WriteLine("Minimum age: " + result.Min);
          Console.WriteLine("Maximum age: " + result.Max);
      }

  }
}
    
class Pet{
   public string Name { get; set; }
   public double Age { get; set; }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System.Linq »




Enumerable