81

How does one convert a KeyValuePair to a Dictionary, given that ToDictionary is not available in C#?

6
  • 1
    Isn't it? Well you could just use var dict = new Dictionary<KeyType, ValueType>() then dict.Add(kvp.Key, kvp.Value)
    – Charleh
    Sep 23, 2013 at 9:02
  • Do a loop and add each KeyValuePair in a new Dictionary.
    – GG.
    Sep 23, 2013 at 9:03
  • 2
    It is a duplicate, Robin incorrectly says C# has no ToDictionary
    – doctorlove
    Sep 23, 2013 at 9:05
  • 1
    @JasonEvans Strictly, it's not a dupe - he is asking how to convert a KeyValuePair, not a List[KeyValuePair]. Of course, this does demand the question "Why does he want to do this"?!!
    – RB.
    Sep 23, 2013 at 9:05
  • 2
    @doctorlove KeyValuePair does not have a ToDictionary method - it's on IEnumerable, and the question (as written) is not talking about an IEnumerable.
    – RB.
    Sep 23, 2013 at 9:05

7 Answers 7

178
var dictionary = new Dictionary<string, object> { { kvp.Key, kvp.Value } };

ToDictionary does exist in C# (edit: not the same ToDictionary you were thinking of) and can be used like this:

using System;
using System.Collections.Generic;
using System.Linq;

var list = new List<KeyValuePair<string, object>>{kvp};
var dictionary = list.ToDictionary(x => x.Key, x => x.Value);

Here list could be a List or other IEnumerable of anything. The first lambda shows how to extract the key from a list item, and the second shows how to extract the value. In this case they are both trivial.

2
  • how can I do that with C# 2.0
    – rikush
    Nov 20, 2018 at 12:41
  • Please add note that you need to use System.Linq
    – Ibrahim
    Jul 1, 2019 at 23:59
8

If I understand correctly you can do it as follows:

new[] { keyValuePair }.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
5

Use System.Linq.Enumerable.ToDictionary() extension method to convert a collection of one or more KeyValuePairs

Dictionary<string,string> result = new[] {  
    new KeyValuePair ("Key1", "Value1"),
    new KeyValuePair ("Key2", "Value2") 
}.ToDictionary(pair => pair.Key, pair => pair.Value);
1

Create a collection of KeyValuePair and make sure System.Linq is imported in a using statement.

Then you will be able to see the .ToDictionary() extension method.

public IList<KeyValuePair<string, object>> MyDictionary { get; set; }
1

Upgrade to .net 5 or higher and pass them to the constructor:

    var x = new Dictionary<string, string>(new[] { new KeyValuePair<string, string>("key1", "val1"), new KeyValuePair<string, string>("key2", "val2") });
0

Alternatively (if you can't use Linq.. although I'm curious why..).. implement ToDictionary yourself...

public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector) {
    if (source == null)
    {
        throw new ArgumentNullException("source");
    }
    if (keySelector == null) {
        throw new ArgumentNullException("keySelector");
    }
    if (elementSelector == null) {
        throw new ArgumentNullException("elementSelector");
    }

    var dictionary = new Dictionary<TKey, TElement>();
    foreach (TSource current in source) {
        dictionary.Add(keySelector(current), elementSelector(current));
    }
    return dictionary;
}

Example usage:

var kvpList = new List<KeyValuePair<int, string>>(){
    new KeyValuePair<int, string>(1, "Item 1"),
    new KeyValuePair<int, string>(2, "Item 2"),
};

var dict = ToDictionary(kvpList, x => x.Key, x => x.Value);
0

Implement it yourself as an extension method.

public static class MyExtensions
{

    public static Dictionary<T1,T2> ToDictionary<T1, T2>(this KeyValuePair<T1, T2> kvp)
    {
      var dict = new Dictionary<T1, T2>();
      dict.Add(kvp.Key, kvp.Value);
      return dict;
    }

}

see this in action: https://dotnetfiddle.net/Ka54t7

3
  • It may not be obvious to some people that the above code cannot be used as-is: One would need to substitute the actual type for T1 and T2, such as string and object...
    – Jazimov
    Jun 3, 2016 at 23:19
  • Oh no, I just forgot one bit
    – br1
    Jun 7, 2016 at 3:22
  • 1
    Jazimov. T1 & T2 are generic type references. You would not substitute them. They are inferred by the KeyValuePair instance being extended. With that said, while this literally answers the question, it isn't useful because you're creating a dictionary collection with only 1 item in its collection. It would be better to extend an IEnumerable of KeyValuePairs, like an array or List. Jul 23, 2020 at 15:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.