Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert KeyValuePair to Dictionary in C#

Tags:

c#

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

like image 801
Robin Joseph Avatar asked Sep 23 '13 09:09

Robin Joseph


People also ask

How to convert list of KeyValuePair to Dictionary?

IDictionary<string, string> dictionary = list. ToDictionary(pair => pair. Key, pair => pair. Value);

How do you turn an object into a dictionary?

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);

How to get Key value pair from Dictionary in c#?

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.

What is the difference between KeyValuePair and dictionary C#?

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.


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

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.

like image 110
jwg Avatar answered Sep 29 '22 07:09

jwg


If I understand correctly you can do it as follows:

new[] { keyValuePair }.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); 
like image 42
BartoszKP Avatar answered Sep 29 '22 06:09

BartoszKP