77

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

bubbleking
  • 3,329
  • 3
  • 29
  • 49
Robin Joseph
  • 1,210
  • 1
  • 11
  • 12
  • 1
    Isn't it? Well you could just use `var dict = new Dictionary()` then `dict.Add(kvp.Key, kvp.Value)` – Charleh Sep 23 '13 at 09:02
  • Do a loop and add each KeyValuePair in a new Dictionary. – GG. Sep 23 '13 at 09:03
  • Not duplicate, he asks without `ToDictionary()`. – GG. Sep 23 '13 at 09:04
  • 2
    It is a duplicate, Robin incorrectly says C# has no ToDictionary – doctorlove Sep 23 '13 at 09: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 '13 at 09: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 '13 at 09:05

7 Answers7

172
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:

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.

jwg
  • 5,547
  • 3
  • 43
  • 57
8

If I understand correctly you can do it as follows:

new[] { keyValuePair }.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
BartoszKP
  • 34,786
  • 15
  • 102
  • 130
4

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);
Antony Booth
  • 413
  • 4
  • 5
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; }
g t
  • 7,287
  • 7
  • 50
  • 85
JSJ
  • 5,653
  • 3
  • 25
  • 32
1

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);
Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138
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") });
Wolfgang Grinfeld
  • 870
  • 10
  • 11
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

br1
  • 313
  • 1
  • 10
  • 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 03 '16 at 23:19
  • Oh no, I just forgot one bit – br1 Jun 07 '16 at 03: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. – Antony Booth Jul 23 '20 at 15:44