Grouping
Method | Description | SQL equivalents |
|---|---|---|
| Groups a sequence into subsequences | |
GroupBy
Argument | Type |
|---|---|
Input sequence | |
Key selector | |
Element selector (optional) | |
Comparer (optional) | |
Return type =
IEnumerable<IGrouping<TSource,TElement>>
Comprehension syntax
groupelement-expressionbykey-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 { ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access