How does one convert a KeyValuePair
to a Dictionary
, given that ToDictionary
is not available in C#?
7 Answers
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.
If I understand correctly you can do it as follows:
new[] { keyValuePair }.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
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);
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; }
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") });
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);
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
-
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...– JazimovJun 3, 2016 at 23:19
-
-
1Jazimov. 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
var dict = new Dictionary<KeyType, ValueType>()
thendict.Add(kvp.Key, kvp.Value)