C# - StringDictionary - 如何使用单个循环获取键和值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1327271/
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
C# - StringDictionary - how to get keys and values using a single loop?
提问by user160677
I am using StringDictionary
collection to collect Key Value Pairs.
我正在使用StringDictionary
集合来收集键值对。
E.g.:
例如:
StringDictionary KeyValue = new StringDictionary();
KeyValue.Add("A", "Load");
KeyValue.Add("C", "Save");
During retrieval i have to form two foreach
to get keys and Values (i.e)
在检索期间,我必须形成两个foreach
以获取键和值(即)
foreach(string key in KeyValue.Values)
{
...
}
foreach(string key in KeyValue.Keys)
{
...
}
Is there any way to get the pair in single foreach
?
有没有办法让这对单身foreach
?
采纳答案by Fredrik M?rk
You can do a foreach
loop on the dictionary, which will give you a DictionaryEntry
in each iteration. You can access the Key
and Value
properties from that object.
您可以foreach
对字典进行循环,这将DictionaryEntry
在每次迭代中为您提供一个。您可以从该对象访问Key
和Value
属性。
foreach (DictionaryEntry value in KeyValue)
{
// use value.Key and value.Value
}
回答by Thorsten Dittmar
One should be enough:
一个就够了:
foreach (string key in KeyValue.Keys)
{
string value = KeyValue[key];
// Process key/value pair here
}
Or did I misunderstand your question?
还是我误解了你的问题?
回答by Anton Gogolev
foreach(DictionaryEntry entry in KeyValue)
{
// ...
}
回答by Mark Seemann
You can simply enumerate over the dictionary itself. It should return a sequence of DictionaryEntry instances.
您可以简单地枚举字典本身。它应该返回一个 DictionaryEntry 实例序列。
A better alternative is to use Dictionary<string, string>
.
更好的选择是使用Dictionary<string, string>
.
回答by Guffa
The StringDictionary can be iterated as DictionaryEntry
items:
StringDictionary 可以作为DictionaryEntry
项目进行迭代:
foreach (DictionaryEntry item in KeyValue) {
Console.WriteLine("{0} = {1}", item.Key, item.Value);
}
I would suggest that you use the more recent Dictionary<string,string>
class instead:
我建议您改用最近的Dictionary<string,string>
课程:
Dictionary<string, string> KeyValue = new Dictionary<string, string>();
KeyValue.Add("A", "Load");
KeyValue.Add("C", "Save");
foreach (KeyValuePair<string, string> item in KeyValue) {
Console.WriteLine("{0} = {1}", item.Key, item.Value);
}
回答by Bruno Reis
You have already many answers. But depending on what you want to do, you can use some LINQ.
你已经有很多答案了。但是根据你想要做什么,你可以使用一些 LINQ。
Let's say you want to get a list of shortcuts that use the CTRL key. You can do something like:
假设您想要获取使用 CTRL 键的快捷方式列表。您可以执行以下操作:
var dict = new Dictionary<string, string>();
dict.Add("Ctrl+A", "Select all");
dict.Add("...", "...");
var ctrlShortcuts =
dict
.Where(x => x.Key.StartsWith("Ctrl+"))
.ToDictionary(x => x.Key, x => x.Value);