Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

C# Dictionary

  1. Home
  2. C# Dictionary
  3. Enumerable.GroupBy()

Enumerable.GroupBy()

A LINQ extension method that groups the elements of a sequence by key. This page also covers ToLookup(), which provides fast key-based access.

Syntax

using System.Linq;

// Group elements by key using a key selector.
IEnumerable<IGrouping<TKey, T>> groups = source.GroupBy(x => key);

// Group elements, specifying the key and value separately.
IEnumerable<IGrouping<TKey, TVal>> groups2 = source.GroupBy(x => key, x => value);

// Create a Lookup that allows direct access by key, similar to a dictionary.
ILookup<TKey, T> lookup = source.ToLookup(x => key);

Method List

MethodDescription
GroupBy(keySelector)Returns an enumeration of IGrouping elements grouped by the key selector.
GroupBy(keySelector, elementSelector)Groups elements while also transforming each element within the group.
GroupBy(keySelector, resultSelector)Returns a result by transforming each group as a whole.
ToLookup(keySelector)Eagerly evaluates and returns a Lookup that maps keys to collections of elements.

Sample Code

using System;
using System.Collections.Generic;
using System.Linq;

var products = new List<(string Name, string Category, int Price)>
{
    ("Apple",   "Fruit",     150),
    ("Mandarin","Fruit",      80),
    ("Carrot",  "Vegetable", 100),
    ("Banana",  "Fruit",     120),
    ("Cabbage", "Vegetable", 200),
};

// Group products by category.
var groups = products.GroupBy(p => p.Category);
foreach (var group in groups)
{
    Console.WriteLine($"[{group.Key}]");
    foreach (var item in group)
        Console.WriteLine($"  {item.Name}: {item.Price}");
}

// Aggregate the count and total price for each group.
var summary = products.GroupBy(p => p.Category)
                       .Select(g => new
                       {
                           Category = g.Key,
                           Count    = g.Count(),
                           Total    = g.Sum(x => x.Price),
                       });
foreach (var s in summary)
    Console.WriteLine($"{s.Category}: {s.Count} items, Total {s.Total}");

// Use ToLookup to quickly access elements by key (eager evaluation).
ILookup<string, string> lookup = products.ToLookup(p => p.Category, p => p.Name);
foreach (var name in lookup["Fruit"])
    Console.WriteLine(name);

Details

GroupBy() uses deferred execution and returns an enumeration of IGrouping<TKey, TElement> representing each group. You can retrieve the group key via the Key property, and enumerate the group directly to access its elements.

ToLookup() uses eager evaluation, making it well suited for cases where you need to look up elements by key multiple times after creation. Unlike Dictionary, ToLookup() does not throw an exception when you access a key that does not exist — it returns an empty sequence instead.

To sort elements after grouping, see Enumerable.OrderBy(). For per-group aggregation, Enumerable.Count() / Sum() / Average() is useful.

If you find any errors or copyright issues, please .