I know that its possible to convert a List of KeyValuePair into a Dictionary, but is the开发者_开发百科re 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.
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>>
.
Using linq:
myDict.ToList<KeyValuePair<double, double>>();
Dictionary elements are KeyValuePair
items.
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.
For .NET 2.0:
Dictionary<TKey, TValue> dictionary = new Dictionary<TKey, TValue>();
List<KeyValuePair<TKey, TValue>> myList = new List<KeyValuePair<TKey, TValue>>(dictionary);
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);
}
精彩评论