C# 迭代字典的最佳方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/141088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the best way to iterate over a dictionary?
提问by Jake Stewart
I've seen a few different ways to iterate over a dictionary in C#. Is there a standard way?
我已经看到了在 C# 中迭代字典的几种不同方法。有标准的方法吗?
采纳答案by Pablo Fernandez
foreach(KeyValuePair<string, string> entry in myDictionary)
{
// do something with entry.Value or entry.Key
}
回答by George Mauer
I would say foreach is the standard way, though it obviously depends on what you're looking for
我会说 foreach 是标准方式,尽管这显然取决于您要查找的内容
foreach(var kvp in my_dictionary) {
...
}
Is that what you're looking for?
这就是你要找的吗?
回答by Jacob
If you are trying to use a generic Dictionary in C# like you would use an associative array in another language:
如果您尝试在 C# 中使用通用字典,就像在另一种语言中使用关联数组一样:
foreach(var item in myDictionary)
{
foo(item.Key);
bar(item.Value);
}
Or, if you only need to iterate over the collection of keys, use
或者,如果您只需要遍历键集合,请使用
foreach(var item in myDictionary.Keys)
{
foo(item);
}
And lastly, if you're only interested in the values:
最后,如果您只对值感兴趣:
foreach(var item in myDictionary.Values)
{
foo(item);
}
(Take note that the var
keyword is an optional C# 3.0 and above feature, you could also use the exact type of your keys/values here)
(请注意,var
关键字是一个可选的 C# 3.0 及更高版本的功能,您也可以在此处使用您的键/值的确切类型)
回答by theo
There are plenty of options. My personal favorite is by KeyValuePair
有很多选择。我个人最喜欢的是 KeyValuePair
Dictionary<string, object> myDictionary = new Dictionary<string, object>();
// Populate your dictionary here
foreach (KeyValuePair<string,object> kvp in myDictionary)
{
// Do some interesting things
}
You can also use the Keys and Values Collections
您还可以使用键和值集合
回答by J Healy
Depends on whether you're after the keys or the values...
取决于您是在追求键还是在追求值...
From the MSDN Dictionary(TKey, TValue)
Class description:
从 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);
}
回答by J Healy
If say, you want to iterate over the values collection by default, I believe you can implement IEnumerable<>, Where T is the type of the values object in the dictionary, and "this" is a Dictionary.
如果说,你想默认遍历values集合,我相信你可以实现IEnumerable<>,其中T是字典中values对象的类型,“this”是一个Dictionary。
public new IEnumerator<T> GetEnumerator()
{
return this.Values.GetEnumerator();
}
回答by J Healy
I found this method in the documentation for the DictionaryBase class on MSDN:
我在 MSDN 上的 DictionaryBase 类的文档中找到了这个方法:
foreach (DictionaryEntry de in myDictionary)
{
//Do some stuff with de.Value or de.Key
}
This was the only one I was able to get functioning correctly in a class that inherited from the DictionaryBase.
这是我能够在继承自 DictionaryBase 的类中正确运行的唯一一个。
回答by J Healy
You suggested below to iterate
您建议在下面进行迭代
Dictionary<string,object> myDictionary = new Dictionary<string,object>();
//Populate your dictionary here
foreach (KeyValuePair<string,object> kvp in myDictionary) {
//Do some interesting things;
}
FYI, foreach
doesn't work if the value are of type object.
仅供参考,foreach
如果值是对象类型,则不起作用。
回答by Maurício Fedatto
In some cases you may need a counter that may be provided by for-loop implementation. For that, LINQ provides ElementAt
which enables the following:
在某些情况下,您可能需要一个由 for 循环实现提供的计数器。为此,LINQ 提供ElementAt
了以下功能:
for (int index = 0; index < dictionary.Count; index++) {
var item = dictionary.ElementAt(index);
var itemKey = item.Key;
var itemValue = item.Value;
}
回答by ender
Sometimes if you only needs the values to be enumerated, use the dictionary's value collection:
有时,如果您只需要枚举值,请使用字典的值集合:
foreach(var value in dictionary.Values)
{
// do something with entry.Value only
}
Reported by this post which states it is the fastest method: http://alexpinsker.blogspot.hk/2010/02/c-fastest-way-to-iterate-over.html
这篇文章报告说它是最快的方法:http: //alexpinsker.blogspot.hk/2010/02/c-fastest-way-to-iterate-over.html