C# Enumerable GroupBy(IEnumerable, Func, Func)
Description
Groups the elements of a sequence according to a specified key selector function and projects the elements for each group by using a specified function.
Syntax
public static IEnumerable<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
Func<TSource, TElement> elementSelector
)/* w w w . j a v a2 s . co m*/
Parameters
TSource
- The type of the elements of source.TKey
- The type of the key returned by keySelector.TElement
- The type of the elements in the IGrouping.source
- An IEnumerablewhose elements to group. keySelector
- A function to extract the key for each element.elementSelector
- A function to map each source element to an element in the IGrouping.
Example
The following code example demonstrates how to use GroupBy to group the elements of a sequence.
/* www. j a va2 s . com*/
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
public static void Main(String[] argv){
List<Pet> pets = new List<Pet>{ new Pet { Name="A", Age=8 },
new Pet { Name="B", Age=4 },
new Pet { Name="C", Age=1 },
new Pet { Name="D", Age=4 } };
IEnumerable<IGrouping<int, string>> query =
pets.GroupBy(pet => pet.Age, pet => pet.Name);
foreach (IGrouping<int, string> petGroup in query)
{
Console.WriteLine(petGroup.Key);
foreach (string name in petGroup)
Console.WriteLine(" {0}", name);
}
}
}
class Pet{
public string Name { get; set; }
public int Age { get; set; }
}
The code above generates the following result.