将项添加到字典是打破foreach循环

时间:2015-01-27 22:58:55

标签: c# loops dictionary foreach ui-automation

我尝试遍历项目集合并将其属性添加到词典中,但由于某种原因它没有完成循环。

我的代码:

Dictionary<string, Tuple<string, string>> elementList = new Dictionary<string, Tuple<string, string>>(); 
public void AddElementList(AutomationElementCollection collection)
{

    foreach (AutomationElement ele in collection)
    {
        elementList.Add(ele.Cached.Name, new Tuple<string, string>(ele.Cached.LocalizedControlType.ToString(), ele.Cached.AutomationId.ToString()));
        i++;

    }
    MessageBox.Show(i.ToString());
}    

它根本没有进入MessageBox.Show。通常有大约52项,它循环8然后退出。

1 个答案:

答案 0 :(得分:0)

你说它经历了8次然后停止。可能是这样的情况,当您在字典上调用Add时它会抛出ArgumentException,因为字典中已存在具有相同键的元素。

这是因为当你去查找字典中的一个值时,它会查找该键,因为如果有两个相同的键,你就不知道要返回哪个值。