Reputation: 789
I know that its possible to convert a List of KeyValuePair into a Dictionary, but is there a quick way (besides looping through manually) to perform the vice versa operation?
This would be the manual way,
foreach (KeyValuePair<double,double> p in dict)
{
list.Add(new KeyValuePair<double,double>(p.Key,p.Value));
}
Not really that bad but I was just curious.
Upvotes: 64
Views: 85857
Reputation: 11903
Like Jason said. But if you don't really need a list, then you can just cast it to an ICollection<TKey, TValue>
; because it implements this interface, but some parts only explicitly. This method performs better because it don't copy the entire list, just reuses the same dictionary instance.
Upvotes: 8
Reputation: 241583
To convert a Dictionary<TKey, TValue>
to a List<KeyValuePair<TKey, TValue>>
you can just say
var list = dictionary.ToList();
or the more verbose
var list = dictionary.ToList<KeyValuePair<TKey, TValue>>();
This is because Dictionary<TKey, TValue>
implements IEnumerable<KeyValuePair<TKey, TValue>>
.
Upvotes: 145
Reputation: 221
I've been trying enumerate an instance of Exception.Data which is an IDictionary. This is what finally worked:
ICollection keys = idict.Keys;
foreach(var key in keys)
{
var value = idict[key];
Console.WriteLine("{0}: {1}", key, value);
}
Upvotes: 0
Reputation: 498904
Using linq:
myDict.ToList<KeyValuePair<double, double>>();
Dictionary elements are KeyValuePair
items.
Upvotes: 8
Reputation: 765
For .NET 2.0:
Dictionary<TKey, TValue> dictionary = new Dictionary<TKey, TValue>();
List<KeyValuePair<TKey, TValue>> myList = new List<KeyValuePair<TKey, TValue>>(dictionary);
Upvotes: 0