.NET API Documentation
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
)
The type of the elements of source.
The type of the keys in the dictionary.
The type of the values in the dictionary.
An IEnumerable<TSource> whose elements will be converted to a dictionary.
A function to extract a key from each element.
A function to pick the value (element) from each element.
A IDictionary<TKey,TElement> that contains keys and values from the input sequence.
Type | Condition |
---|---|
ArgumentNullException | source, keySelector, or elementSelector is null. |
ArgumentException | One or more keys are duplicated. |
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.
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}");
}
}
}