[英]Iterate over Dictionary in C#
我正在创建一个Dictionary,并将字符串添加为键,并将另一个Dictionary添加为引用特定用户的值。 我无法遍历键(字典中的字符串),如果符合我的要求,则需要获取该字典中的值。
就像是 :
Dictionary<string,Dictionary<string,string>> myDictionary = new Dictionary<string,Dictionary<string,string>>
mydictionary.Add(string,Dictionary<string,string>)
这是我想做的事:
foreach(string s in Dictionary<string,Dictionary>)
{ if(s.contains("Foo")) {
return the dictionary which is mapped to this key.
}
}
这是Linq一线客车,应该可以满足您的需求...
return myDictionary
.Where(kvp => kvp.Key.Contains("Foo"))
.Select(kvp => kvp.Value)
.FirstOrDefault();
像这样吗
foreach (var s in myDictionary.Keys)
{
if (s.Contains("Foo"))
return myDictionary[s];
}
如果只想返回内部字典(值),则应使用TryGetValue
,这是最佳性能方法:
Dictionary<string, string> values;
if (dictionary.TryGetValue("Foo", out values) && values != null)
{
// do something with the value
}
如果那不适合您的需求,则可以根据需要遍历键或键值对:
foreach (KeyValuePair<string, Dictionary<string, string>> kvp in dictionary)
{
if(kvp.Key.Contains("Foo"))
{
var dictionary = kvp.Value;
}
}
Dictionary<string, Dictionary<string, string>> myDictionary = new Dictionary<string, Dictionary<string, string>>();
Dictionary<String, string> di = new Dictionary<string, string>();
di.Add("1", "Hello1");
myDictionary.Add("Item1", di);
di.Add("2", "Hello2");
myDictionary.Add("Item2", di);
di.Add("3", "Hello3");
myDictionary.Add("Item3", di);
var result = myDictionary.Where(c => c.Key == "Item1").FirstOrDefault();
if (result.Key != null)
{
Dictionary<string, string> output = result.Value;
}
尝试这种方式。
foreach(DictionaryEntry Item in myDictionary){
Console.WrileLine("Name : "+ Item.Key+" Value"+Item.value.toString());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.