-
Notifications
You must be signed in to change notification settings - Fork 5.2k
Closed
Labels
api-approvedAPI was approved in API review, it can be implementedAPI was approved in API review, it can be implementedarea-System.Collectionshelp wanted[up-for-grabs] Good issue for external contributors[up-for-grabs] Good issue for external contributors
Milestone
Description
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
theodorzoulias, martincostello, Joe4evr, omariom, AmrAlSayed0 and 8 moreMrxx99, dersia and CZEMacLeod
Metadata
Metadata
Assignees
Labels
api-approvedAPI was approved in API review, it can be implementedAPI was approved in API review, it can be implementedarea-System.Collectionshelp wanted[up-for-grabs] Good issue for external contributors[up-for-grabs] Good issue for external contributors