Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

Enumerable.ToDictionary: practical reference

Enumerable.ToDictionary: practical reference: Immediately enumerates and builds a Dictionary<TKey,TValue> from selected keys and optional selected values.

Version: .NET LINQ; verified on .NET 10.0.14

Syntax

source.ToDictionary(/* overload-specific arguments */)

Immediately enumerates and builds a Dictionary<TKey,TValue> from selected keys and optional selected values.

Use it for a single-value index when every key must be unique.

A duplicate key throws ArgumentException; choose ToLookup for multiple values. The comparer defines key equality.

A null key is forbidden by the relevant dictionary contract. A null source or selector causes ArgumentNullException.

The complete program actually uses Enumerable.ToDictionary; its exact expected stdout is bee.

Examples

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

var map = new[] { "ant", "bee" }.ToDictionary(word => word[0]);
Console.WriteLine(map['b']);

Result

bee

The complete program actually uses `Enumerable.ToDictionary`; its exact expected stdout is `bee`.

Sources