O'Reilly logo

LINQ Pocket Reference by Joseph Albahari, Ben Albahari

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 { ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required