My scenario,
how to convert List<KeyValuePair<string, string>>
into IDictionary<string, string>
?
IDictionary<string, string> dictionary = list. ToDictionary(pair => pair. Key, pair => pair. Value);
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.
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. d.
To start, we include the System.Collections.Generic and System.Linq namespaces. We create and populate a Dictionary collection. Next, we call ToList () on that Dictionary collection, yielding a List of KeyValuePair instances. Then: We loop over the List instance, using a foreach-loop with the KeyValuePair iteration variable.
It's easy to create a List<KeyValuePairs<T1, T2>>, and conceptually, it's the same thing as a Dictionary, but I just couldn't find a way to convert. The ToDictionary () extension method allows you to specify which parts of your list item you want for a key and value, including the key/value of KeyValuePair<> list item.
ToList is part of the System.Linq extensions to the C# language. Example. To start, we include the System.Collections.Generic and System.Linq namespaces. We create and populate a Dictionary collection. Next, we call ToList () on that Dictionary collection, yielding a List of KeyValuePair instances.
Convert dictionary, list. A Dictionary can be converted into a List. Specifically it is converted to a List of pairs. This requires the ToList extension method. ToList is part of the System.Linq extensions to the C# language. Example. To start, we include the System.Collections.Generic and System.Linq namespaces.
Very, very simply with LINQ:
IDictionary<string, string> dictionary = list.ToDictionary(pair => pair.Key, pair => pair.Value);
Note that this will fail if there are any duplicate keys - I assume that's okay?
Or you can use this extension method to simplify your code:
public static class Extensions { public static IDictionary<TKey, TValue> ToDictionary<TKey, TValue>( this IEnumerable<KeyValuePair<TKey, TValue>> list) { return list.ToDictionary(x => x.Key, x => x.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