Skip to content

[API Proposal]: Enhance dictionary and set constructors/factories with Duplicate Key Handling Options #113096

Open

Description

@granitbunjaku

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 foreach loop 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 of ToDictionary remains 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

  1. ghost added
    needs-area-label
    on Mar 3, 2025
  2. added
    untriaged
    on Mar 3, 2025
  3. julealgon commented on Mar 3, 2025

    @julealgon

    I think this would be useful in multiple overloads and not just that one though. The one that takes IEnumerable<ValueTuple and IEnumerable<KeyValuePair come to mind immediately.

  4. removed
    needs-area-label
    on Mar 6, 2025
  5. jeffhandley commented on Jul 26, 2025

    @jeffhandley
    Member

    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.

  6. added
    needs-further-triage
    and removed
    untriaged
    on Jul 26, 2025
  7. added this to the Future milestone on Jul 26, 2025
  8. granitbunjaku commented on Jul 26, 2025

    @granitbunjaku
    Author

    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.

  9. added
    api-ready-for-review
    and removed
    needs-further-triage
    on Jul 26, 2025
  10. changed the title [-]Proposal: Enhance ToDictionary with Duplicate Key Handling Options[/-] [+][API Proposal]: Enhance ToDictionary with Duplicate Key Handling Options[/+] on Jul 26, 2025
  11. GrabYourPitchforks commented on Aug 19, 2025

    @GrabYourPitchforks
    Member

    there are many common scenarios where developers need to handle duplicates gracefully

    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.

  12. dersia commented on Aug 31, 2025

    @dersia

    I would prefer (Take)First and (Take)Last over Override and Ignore. it makes it a bit clearer what to expect.

    Maybe it makes sense to also add an options that takes a MergFunction

        Dictonary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(this IEnumerable<TSource> source, Func<TSource, TKey> keyFunction, Func<TSource, TElement> valueFunction, Func<TSource, TElement, TElement> merge Function);
  13. 1 remaining item

  14. lilinus commented on Sep 19, 2025

    @lilinus
    Contributor

    Do we want to review adding relevant ToDictionaryAsync overloads to AsyncEnumerable too?

  15. leotsarev commented on Oct 13, 2025

    @leotsarev
    Contributor

    My case is performance:

    var largeDict = largeListOfItems.DistinctBy(item => item.KeyId).ToDictionary(item => item.KeyId);

    DistinctBy() will reallocate internal hashset couple of times, then ToDictionary() will reallocate dictionary another couple of times.

  16. bartonjs commented on Nov 25, 2025

    @bartonjs
    Member

    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.

  17. added
    api-needs-work
    and removed
    api-ready-for-review
    on Nov 25, 2025
  18. eiriktsarpalis commented on Nov 26, 2025

    @eiriktsarpalis
    Member

    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:

    1. The enum should be moved to the System.Collections.Generic (or System.Collections?) namespace. We think the naming needs a bit of work.
    2. We should augment collection constructors accepting IEnumerable with overloads accepting this enum in dictionary and set types
    3. We should include ToDictionary and ToHashSet overloads as proposed here.
    4. We should look into the potential interaction of this feature with dictionary literals cc @CyrusNajmabadi
  19. datvm commented on Dec 9, 2025

    @datvm

    I want to add that ToFrozenDictionary should 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 like DuplicateKeyHandling.Override suggested).

    This behavior is only documented in the Remarks section which does not even show up on the IntelliSense tooltip.

    From my post:

    This has been quite annoying to me because I use it a lot and I have to be careful when using it. I usually intentionally want it to throw if there is key duplicates (from library).

    In what use case is it actually useful to just let the latter value overwrite the former? I haven't come across a single time that I want that behavior. I know the behavior can't be changed anymore but maybe suggesting a ToFrozenDictionaryStrict() function is not unreasonable?

  20. TonyValenti commented on Dec 10, 2025

    @TonyValenti

    We'd like this as well. We've had to roll our own variants to handle this.

  21. ladeak commented on Dec 11, 2025

    @ladeak
    Contributor

    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 factoryArgument parameter that lets the consumer of the API to select which value to use or how to merge them.
    Similar to what @dersia mentioned above.

  22. CyrusNajmabadi commented on Dec 11, 2025

    @CyrusNajmabadi
    Contributor

    We should look into the potential interaction of this feature with dictionary literals cc @CyrusNajmabadi

    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.

  23. changed the title [-][API Proposal]: Enhance ToDictionary with Duplicate Key Handling Options[/-] [+][API Proposal]: Enhance dictionary and set constructors/factories with Duplicate Key Handling Options[/+] on Dec 11, 2025
  24. jnm2 commented on Dec 12, 2025

    @jnm2
    Contributor

    There could be interest in [with(DuplicateKeyHandling.ThrowError), .. dict1, .. dict2]. Currently, for such a thing to work, either Dictionary<,> would have to be given a constructor that takes a single DuplicateKeyHandling parameter, or Dictionary<,> 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.)

  25. eiriktsarpalis commented on Dec 12, 2025

    @eiriktsarpalis
    Member

    There could be interest in [with(DuplicateKeyHandling.ThrowError), .. dict1, .. dict2]

    I think that would be useful, particularly if we're applying the spread operator to enumerables coming from untrusted inputs.

  26. jnm2 commented on Dec 12, 2025

    @jnm2
    Contributor

    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), ...]
    • Other combinations of DuplicateKeyHandling, int capacity, and IEqualityComparer<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.

  27. ladeak commented on Dec 12, 2025

    @ladeak
    Contributor

    I struck out the one route of adding a Dictionary<,> constructor that takes a single DuplicateKeyHandling parameter.

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-needs-workarea-System.Runtime

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions