KEMBAR78
[API Proposal]: Add overload of ToDictionary that turns an IEnumerable of KeyValuePair or ValueTuple · Issue #65925 · dotnet/runtime · GitHub
Skip to content

[API Proposal]: Add overload of ToDictionary that turns an IEnumerable of KeyValuePair or ValueTuple #65925

@davidfowl

Description

@davidfowl

Background and motivation

Sometimes in parsing it's common transform key value pairs expressed as text into a dictionary pretty concise LINQ statement: Consider a query string parser (a=b&c=d&e=f).

Dictionary<string, string> Parse(string query) =>
    query.Split('&')
    .Select<string, (string k, string v)?>(s => s.Split('=') switch // This part is gross 😢 
    {
        [var k, var v] => (k, v),
        _ => null,
    })
    .Where(p => p is not null)
    .Select(p => p!.Value)
    .ToDictionary(p => p.k!, p => p.v!);

The last ToDictionary call wouldn't require explicitly mapping the key and value for this common case.

API Proposal

namespace System.Collections.Generic;

public static partial class Enumerable
{
    public static Dictionary<TKey, TValue> ToDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> source) where TKey : notnull;
    public static Dictionary<TKey, TValue> ToDictionary<TKey, TValue>(this IEnumerable<ValueTuple<TKey, TValue>> source) 
where TKey : notnull;
    public static Dictionary<TKey, TValue> ToDictionary<TKey, TValue>(this IEnumerable<ValueTuple<TKey, TValue>> source, IEqualityComparer<TKey> comparer) where TKey : notnull;
}

API Usage

// Fancy the value
var c = new List<(string, int)>();
c.Add(("one", 1));
c.Add(("two", 2));
c.Add(("three", 3));

var map = c.ToDictionary();

// Getting the values out
foreach (var (key, value) in map)
    Console.WriteLine($"{key} = {value}");

Alternative Designs

No response

Risks

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-approvedAPI was approved in API review, it can be implementedarea-System.Collectionshelp wanted[up-for-grabs] Good issue for external contributors

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions