Grouping

Method

Description

SQL equivalents

GroupBy

Groups a sequence into subsequences

GROUP BY

GroupBy

Argument

Type

Input sequence

IEnumerable<TSource>

Key selector

TSource => TKey

Element selector (optional)

TSource => TElement

Comparer (optional)

IEqualityComparer<TKey>

Return type = IEnumerable<IGrouping<TSource,TElement>>

Comprehension syntax

	group element-expression by key-expression

Overview

GroupBy organizes a flat input sequence into sequences of groups. For example, the following organizes all the files in c:\temp by extension:

	string[] files = Directory.GetFiles("c:\\temp");

	IEnumerable<IGrouping<string,string>> query =
	  files.GroupBy (file => Path.GetExtension (file));

or if you’re comfortable with implicit typing:

	var query = files.GroupBy
	  (file => Path.GetExtension (file));

Here’s how to enumerate the result:

	foreach (IGrouping<string,string>grouping in query)
	{
	  Console.WriteLine("Extension: " + grouping.Key);

	  foreach (string filename in grouping)
	    Console.WriteLine ("   - " + filename);
	}

	Extension: .pdf
	  -- chapter03.pdf
	  -- chapter04.pdf

	Extension: .doc
	  -- todo.doc
	  -- menu.doc
	  -- Copy of menu.doc
	...

Enumerable.GroupBy works by reading the input elements into a temporary dictionary of lists so that all elements with the same key end up in the same sublist. It then emits a sequence of groupings. A grouping is a sequence with a Key property:

 public interface IGrouping <TKey,TElement> : IEnumerable<TElement>, IEnumerable { // Key applies to the subsequence as a whole TKey Key { ...

Get LINQ Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.