System.Linq.ToDictionary

.NET API Documentation

Namespace: System.Linq

Extension Method

Converts an IEnumerable<TSource> to a IDictionary<TKey,TElement> by the specified key selector and element selector functions.

Syntax

public static System.Collections.Generic.IDictionary<TKey,TElement> ToDictionary<TSource, TKey, TElement>( this System.Collections.Generic.IEnumerable<TSource> source, System.Func<TSource,TKey> keySelector, System.Func<TSource,TElement> elementSelector )

Type Parameters

Parameters

Returns

IDictionary<TKey,TElement>

A IDictionary<TKey,TElement> that contains keys and values from the input sequence.

Exceptions

Type Condition
ArgumentNullException source, keySelector, or elementSelector is null.
ArgumentException One or more keys are duplicated.

Remarks

This is an extension method and can be called using the syntax `ienumerable.ToDictionary(...)`.

The order of elements in the resulting dictionary is not guaranteed.

If the source sequence contains duplicate keys, an ArgumentException is thrown.

Example

using System; using System.Collections.Generic; using System.Linq; public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } } public class Example { public static void Main() { List<Product> products = new List<Product> { new Product { Id = 1, Name = "Laptop", Price = 1200.00m }, new Product { Id = 2, Name = "Keyboard", Price = 75.50m }, new Product { Id = 3, Name = "Mouse", Price = 25.00m } }; // Create a dictionary where Product Id is the key and Product Name is the value Dictionary<int, string> productNamesById = products.ToDictionary(p => p.Id, p => p.Name); Console.WriteLine("Product names by ID:"); foreach (var kvp in productNamesById) { Console.WriteLine($"ID: {kvp.Key}, Name: {kvp.Value}"); } // Create a dictionary where Product Name is the key and Product Price is the value Dictionary<string, decimal> productPricesByName = products.ToDictionary(p => p.Name, p => p.Price); Console.WriteLine("\nProduct prices by Name:"); foreach (var kvp in productPricesByName) { Console.WriteLine($"Name: {kvp.Key}, Price: {kvp.Value:C}"); } } }
.NET Core 1.0, .NET Framework 3.5, Mono, Xamarin.Android, Xamarin.iOS, Xamarin.Mac