迭代字典的最佳方法是什么?
时间:2020-03-06 14:47:53 来源:igfitidea点击:
我已经看到了几种不同的方法来遍历C#中的字典。有没有标准的方法?
解决方案
foreach(KeyValuePair<string, string> entry in myDictionary)
{
// do something with entry.Value or entry.Key
}
我会说foreach是标准方式,尽管它显然取决于我们要查找的内容
foreach(var kvp in my_dictionary) {
...
}
那是我们要找的东西吗?
如果我们尝试在Clike中使用通用词典,则可以使用另一种语言的关联数组:
foreach(var item in myDictionary)
{
foo(item.Key);
bar(item.Value);
}
或者,如果只需要遍历键的集合,请使用
foreach(var item in myDictionary.Keys)
{
foo(item);
}
最后,如果我们仅对值感兴趣:
foreach(var item in myDictionary.Values)
{
foo(item);
}
(请注意,关键字var是C3.0及更高版本的可选功能,我们也可以在此处使用键/值的确切类型)
有很多选择。我个人最喜欢的是KeyValuePair
Dictionary<string, object> myDictionary = new Dictionary<string, object>();
// Populate your dictionary here
foreach (KeyValuePair<string,object> kvp in myDictionary)
{
// Do some interesting things
}
我们还可以使用"键和值"集合
取决于我们要使用的是键还是值...
从MSDNDictionary(TKey,TValue)类描述:
// When you use foreach to enumerate dictionary elements,
// the elements are retrieved as KeyValuePair objects.
Console.WriteLine();
foreach( KeyValuePair<string, string> kvp in openWith )
{
Console.WriteLine("Key = {0}, Value = {1}",
kvp.Key, kvp.Value);
}
// To get the values alone, use the Values property.
Dictionary<string, string>.ValueCollection valueColl =
openWith.Values;
// The elements of the ValueCollection are strongly typed
// with the type that was specified for dictionary values.
Console.WriteLine();
foreach( string s in valueColl )
{
Console.WriteLine("Value = {0}", s);
}
// To get the keys alone, use the Keys property.
Dictionary<string, string>.KeyCollection keyColl =
openWith.Keys;
// The elements of the KeyCollection are strongly typed
// with the type that was specified for dictionary keys.
Console.WriteLine();
foreach( string s in keyColl )
{
Console.WriteLine("Key = {0}", s);
}
如果说,我们想默认情况下遍历值集合,我相信我们可以实现IEnumerable <>,其中T是字典中value对象的类型,而" this"是Dictionary。
public new IEnumerator<T> GetEnumerator()
{
return this.Values.GetEnumerator();
}
我在MSDN上的DictionaryBase类的文档中找到此方法:
foreach (DictionaryEntry de in myDictionary)
{
//Do some stuff with de.Value or de.Key
}
这是我唯一能够在从DictionaryBase继承的类中正常运行的函数。
我们建议在下面进行迭代
Dictionary<string,object> myDictionary = new Dictionary<string,object>();
//Populate your dictionary here
foreach (KeyValuePair<string,object> kvp in myDictionary) {
//Do some interesting things;
}
仅供参考,如果值是object类型,则foreach不起作用。

