Sea*_*ean 47 c# generics collections
我知道可以将KeyValuePair的List转换为Dictionary,但是有一种快速的方法(除了手动循环)以执行相反的操作吗?
这将是手动方式,
foreach (KeyValuePair<double,double> p in dict)
{
list.Add(new KeyValuePair<double,double>(p.Key,p.Value));
}
Run Code Online (Sandbox Code Playgroud)
不是那么糟糕,但我只是好奇.
jas*_*son 112
要将a转换Dictionary<TKey, TValue>为a,List<KeyValuePair<TKey, TValue>>你可以说
var list = dictionary.ToList();
Run Code Online (Sandbox Code Playgroud)
或者更冗长
var list = dictionary.ToList<KeyValuePair<TKey, TValue>>();
Run Code Online (Sandbox Code Playgroud)
这是因为Dictionary<TKey, TValue>工具IEnumerable<KeyValuePair<TKey, TValue>>.
使用linq:
myDict.ToList<KeyValuePair<double, double>>();
Run Code Online (Sandbox Code Playgroud)
字典元素是 KeyValuePair项目.
像杰森说的那样.但是如果你真的不需要列表,那么你可以将它转换为ICollection <TKey,TValue>,因为它实现了这个接口,但是某些部分只是显式的.此方法执行得更好,因为它不复制整个列表,只是重用相同的字典实例.