在C#中迭代字典

时间:2015-03-02 13:50:24

标签: c# dictionary

我正在创建一个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.
}
}

5 个答案:

答案 0 :(得分:4)

这是一个Linq单行程,可以做你需要的......

return myDictionary
    .Where(kvp => kvp.Key.Contains("Foo"))
    .Select(kvp => kvp.Value)
    .FirstOrDefault();

答案 1 :(得分:1)

这样的东西?

foreach (var s in myDictionary.Keys)
{
    if (s.Contains("Foo"))
        return myDictionary[s];
}

答案 2 :(得分:1)

如果您只想返回内部字典(值),则应使用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;
    }
}

答案 3 :(得分:0)

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;
            }

答案 4 :(得分:-1)

尝试这种方式。

foreach(DictionaryEntry Item in myDictionary){
  Console.WrileLine("Name : "+ Item.Key+" Value"+Item.value.toString());
}