简体   繁体   English

在字典中添加项目打破了foreach循环

[英]Adding Item to Dictionary is breaking foreach loop

I'm trying to loop through a collection of items and add their properties to a Dictionary, though for some reason its not finishing the loop. 我试图遍历项目的集合并将其属性添加到Dictionary中,尽管由于某种原因它无法完成循环。

My code: 我的代码:

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

Its not getting to the MessageBox.Show at all. 它根本没有进入MessageBox.Show。 There is usually around 52 items, it loops through 8 then quits. 通常大约有52个项目,它循环8次然后退出。

You say that it goes through 8 times then stops. 您说它经过8次然后停止。 It may be the case that when you call Add on the dictionary that it throws an ArgumentException because An element with the same key already exists in the Dictionary. 可能的情况是,当您在字典上调用Add时,它会引发ArgumentException,因为在字典中已经存在具有相同键的元素。

This happens because when you go to look up a value in a dictionary, that it looks for that key, of cause if there were two of the same key, you wouldn't know which value to return. 发生这种情况的原因是,当您在字典中查找一个值时,它会寻找那个键,因为如果有两个相同的键,您将不知道要返回哪个值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM