Repository navigation
Description
Background and motivation
The Enumerable.ToDictionary extension method is a highly convenient way to convert a collection into a dictionary. However, its current implementation immediately throws an ArgumentException if any duplicate keys are found in the source IEnumerable. While this is often the desired, fail-fast behavior, there are many common scenarios where developers need to handle duplicates gracefully.
Currently, developers must resort to more verbose and less discoverable workarounds to manage duplicates, such as:
- Using
GroupBy(keySelector).ToDictionary(g => g.Key, g => g.Last())to get the last element. - Using a
foreachloop and manually adding items to a dictionary. - Using
.DistinctBy(keySelector)before.ToDictionary(...).
These approaches add boilerplate code, can be less performant due to intermediate allocations (e.g., GroupBy), and obscure the original intent.
Adding built-in support for duplicate key handling directly within ToDictionary would improve usability, reduce boilerplate, and increase performance by providing a clean, discoverable, and optimized solution.
API Proposal
We propose introducing a new enum to control the behavior when a duplicate key is encountered and adding new overloads to ToDictionary that accept it.
1. The DuplicateKeyHandling Enum
namespace System.Linq
{
public enum DuplicateKeyHandling
{
/// <summary>Throws an ArgumentException if a duplicate key is found. This is the default behavior.</summary>
ThrowError,
/// <summary>If a duplicate key is found, the existing entry is overridden with the new one.</summary>
Override,
/// <summary>If a duplicate key is found, the new entry is ignored and the existing one is kept.</summary>
Ignore
}
}2. New ToDictionary Overloads
The new duplicateHandling parameter should be added to all relevant ToDictionary overloads with a default value of ThrowError to maintain backward compatibility.
namespace System.Linq
{
public static class Enumerable
{
// Overload with just a key selector
public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
DuplicateKeyHandling duplicateHandling = DuplicateKeyHandling.ThrowError) where TKey : notnull;
// Overload with a key selector and a comparer
public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
IEqualityComparer<TKey>? comparer,
DuplicateKeyHandling duplicateHandling = DuplicateKeyHandling.ThrowError) where TKey : notnull;
// Overload with key and element selectors
public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
Func<TSource, TElement> elementSelector,
DuplicateKeyHandling duplicateHandling = DuplicateKeyHandling.ThrowError) where TKey : notnull;
// Overload with key/element selectors and a comparer
public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
Func<TSource, TElement> elementSelector,
IEqualityComparer<TKey>? comparer,
DuplicateKeyHandling duplicateHandling = DuplicateKeyHandling.ThrowError) where TKey : notnull;
}
}API Usage
Setup:
public record Product(int Id, string Name);
var products = new List<Product>
{
new(1, "Book"),
new(2, "Chair"),
new(1, "eBook (updated)") // Duplicate ID
};Example 1: Override (Last one wins)
This is useful for processing a dataset where you only care about the most recent entry.
// The entry for key '1' will be the "eBook (updated)" product.
Dictionary<int, Product> finalProducts = products.ToDictionary(
p => p.Id,
DuplicateKeyHandling.Override);
// Result: { 1: Product(1, "eBook (updated)"), 2: Product(2, "Chair") }Example 2: Ignore (First one wins)
This is useful when you want to take the first entry encountered and ignore all subsequent duplicates.
// The entry for key '1' will be the original "Book" product.
Dictionary<int, string> productNames = products.ToDictionary(
p => p.Id,
p => p.Name,
DuplicateKeyHandling.Ignore);
// Result: { 1: "Book", 2: "Chair" }Alternative Designs
The primary alternative is to maintain the status quo, forcing users to continue using workarounds like GroupBy. This was rejected because it is less efficient and less ergonomic.
Another alternative would be to introduce new methods, like ToDictionaryOverrideDuplicates() or ToDictionaryIgnoreDuplicates(). This was deemed less ideal as it clutters the API surface. Using an enum is a more scalable and cleaner approach that groups related functionality under a single, well-known method.
Risks
The risk associated with this proposal is very low.
- No Breaking Changes: By defaulting to
ThrowError(either implicitly via new overloads or explicitly with an optional parameter), the existing behavior ofToDictionaryremains unchanged. All existing code will continue to compile and work as expected. - Minimal API Complexity: The new functionality is opt-in. Developers who do not need duplicate handling will not be impacted.
Activity
julealgon commentedon Mar 3, 2025
I think this would be useful in multiple overloads and not just that one though. The one that takes
IEnumerable<ValueTupleandIEnumerable<KeyValuePaircome to mind immediately.jeffhandley commentedon Jul 26, 2025
The issue description should be edited to match the API Suggestion issue template and to include the other overloads @julealgon mentioned and perhaps others, but the proposal is interesting.
granitbunjaku commentedon Jul 26, 2025
Thanks for the feedback, @jeffhandley . I've updated the issue description to match the API proposal template and included the other overloads as you suggested.
[-]Proposal: Enhance ToDictionary with Duplicate Key Handling Options[/-][+][API Proposal]: Enhance ToDictionary with Duplicate Key Handling Options[/+]GrabYourPitchforks commentedon Aug 19, 2025
This is stated as a given fact, but no scenarios are listed. Listing these scenarios would strengthen the case to be made for introducing this API.
dersia commentedon Aug 31, 2025
I would prefer
(Take)Firstand(Take)LastoverOverrideandIgnore. it makes it a bit clearer what to expect.Maybe it makes sense to also add an options that takes a MergFunction
1 remaining item
lilinus commentedon Sep 19, 2025
Do we want to review adding relevant
ToDictionaryAsyncoverloads toAsyncEnumerabletoo?leotsarev commentedon Oct 13, 2025
My case is performance:
DistinctBy()will reallocate internal hashset couple of times, thenToDictionary()will reallocate dictionary another couple of times.bartonjs commentedon Nov 25, 2025
Video
API Review: This came up in discussion, but the feeling by the area owner was that it wasn't ready, so marking as needs-work.
eiriktsarpalis commentedon Nov 26, 2025
To add more context, we think that this is a useful feature which should be extended beyond the narrow scope of LINQ. In other words:
System.Collections.Generic(orSystem.Collections?) namespace. We think the naming needs a bit of work.IEnumerablewith overloads accepting this enum in dictionary and set typesToDictionaryandToHashSetoverloads as proposed here.datvm commentedon Dec 9, 2025
I want to add that
ToFrozenDictionaryshould support this as well but for the opposite reason! For some strange reason I think this is the only Dictionary API that does NOT throw on duplicate (but is behaving likeDuplicateKeyHandling.Overridesuggested).This behavior is only documented in the Remarks section which does not even show up on the IntelliSense tooltip.
From my post:
TonyValenti commentedon Dec 10, 2025
We'd like this as well. We've had to roll our own variants to handle this.
ladeak commentedon Dec 11, 2025
An alternative (or maybe just an additional overload) to this design could be something like the AddOrUpdate method with an additional
Func<TKey,TValue,TArg,TValue> updateValueFactory, TArg factoryArgumentparameter that lets the consumer of the API to select which value to use or how to merge them.Similar to what @dersia mentioned above.
CyrusNajmabadi commentedon Dec 11, 2025
Interesting question. Paging in @jnm2 @333fred and @RikkiGibson .
off the top of my head (so giving VERY little thought to this), i wasn't thinking we'd be using ToDictionary at all. Instead, we'd be constructing the dict and using the indexer to overwrite things. So i dno't think there's an overlap currently.
But, generally speaking, i'm in favor of this. Being able to specify overwrite semantics is nice, and aligns exactly with the view that dict-exprs has that you get overwrite semantics on consturction of a dict type.
[-][API Proposal]: Enhance ToDictionary with Duplicate Key Handling Options[/-][+][API Proposal]: Enhance dictionary and set constructors/factories with Duplicate Key Handling Options[/+]jnm2 commentedon Dec 12, 2025
There could be interest in
[with(DuplicateKeyHandling.ThrowError), .. dict1, .. dict2]. Currently, for such a thing to work,eitherDictionary<,>would have to be given a constructor that takes a single DuplicateKeyHandling parameter, orDictionary<,>would have to have a[CollectionBuilder]attribute added which points to a Create/CreateRange method group that has an overload with a DuplicateKeyHandling parameter.(DuplicateKeyHandling.Override will be the behavior of dictionary expressions in general as Cyrus says, and Ignore will be achievable by reversing the order of the expressions within the dictionary expression.)
eiriktsarpalis commentedon Dec 12, 2025
I think that would be useful, particularly if we're applying the spread operator to enumerables coming from untrusted inputs.
jnm2 commentedon Dec 12, 2025
On further thought, I struck out the one route of adding a
Dictionary<,>constructor that takes a single DuplicateKeyHandling parameter. That would only work as intended on[with(DuplicateKeyHandling.ThrowError), .. dict1, .. dict2]if the constructor parameter changed the behavior of future indexer calls to throw on overwrites, but I would expect that to be semantically undesirable. The final constructed dictionary should probably allow overwrites via the indexer even after ThrowError was used in its initial creation.Therefore, the only remaining affordance that is currently planned would be for
Dictionary<,>to get a[CollectionBuilder]attribute pointing at a Create/CreateRange method group on a nongeneric class. That method group would need to include the following signatures:(ReadOnlySpan<KeyValuePair<TKey, TValue>>)(to preserve parity with the
Dictionary()constructor)(ReadOnlySpan<KeyValuePair<TKey, TValue>>, IEqualityComparer<TKey>)(to preserve parity with the
Dictionary(IEqualityComparer<TKey>)constructor)(ReadOnlySpan<KeyValuePair<TKey, TValue>>, int)(to preserve parity with the
Dictionary(int)constructor)(ReadOnlySpan<KeyValuePair<TKey, TValue>>, int, IEqualityComparer<TKey>)(to preserve parity with the
Dictionary(int, IEqualityComparer<TKey>)constructor)(ReadOnlySpan<KeyValuePair<TKey, TValue>>, DuplicateKeyHandling duplicateKeyHandling)(to enable
[with(DuplicateKeyHandling.Xyz), ...]int capacity, andIEqualityComparer<TKey>, maybe a single additional overload with optional parameters, to enable[with(capacity, comparer, DuplicateKeyHandling.ThrowError), ...]This is a lot of API surface to add to enable DuplicateKeyHandling to be controlled in a dictionary expression. Would that be at all palatable to do? If it's an important scenario, but the above is too much API surface for the runtime to add, perhaps we could take that feedback to influence the collection-expression-args feature while it's still being worked on.
ladeak commentedon Dec 12, 2025
I agree with this, as adding such ctor parameter is giving the impression that this inherently known by the Dictionary, however serialization - deserialization (json, protobuff) does not keep the behavior.