How does one convert a KeyValuePair
to a Dictionary
, given that ToDictionary
is not available in C#?
IDictionary<string, string> dictionary = list. ToDictionary(pair => pair. Key, pair => pair. Value);
I found it easy to json serialize the object and deserialize as a dictionary. var json = JsonConvert. SerializeObject(obj); var dictionary = JsonConvert. DeserializeObject<Dictionary<string, string>>(json);
To add key-value pair in C# Dictionary, firstly declare a Dictionary. IDictionary<int, string> d = new Dictionary<int, string>(); Now, add elements with KeyValuePair.
KeyValuePair is the unit of data stored in a Hashtable (or Dictionary ). They are not equivalent to each other. A key value pair contains a single key and a single value. A dictionary or hashtable contains a mapping of many keys to their associated values.
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.
If I understand correctly you can do it as follows:
new[] { keyValuePair }.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With