【问题标题】:System.NotSupportedException: 'Collection is read-only.' thrown when removing object from iListSystem.NotSupportedException:“集合是只读的。”从 iList 中删除对象时抛出
【发布时间】:2018-02-21 13:42:26
【问题描述】:

运行下面代码的 sn-p 时抛出异常。

我有一个 iListof webelements,如果该元素包含字符串“WSC”,我想将其从 iList 中删除。

谁能帮帮我?代码如下。

IList<IWebElement> tableRows;
        tableRows = FindElement(By.XPath("//div[@ui-grid='vm.gridWoodSmokeViolations']")).FindElements(By.XPath("//div[@role='row']"));
        Console.WriteLine("table row count before loop: " + tableRows.Count);
        foreach (var row in tableRows) {

            if (row.Text.ToString().Contains("WSC"))
            {

                tableRows.Remove(row); //exception thrown here

            }

        }

感谢您提供的任何帮助

【问题讨论】:

  • 在使用foreach 循环遍历集合时不要修改集合。尝试使用for 循环,例如in this answer。或者找到要删除的项目,保存对它的引用(LINQ 可以在此处提供帮助),然后在 循环之后将其删除。
  • @Jonesopolis 我将如何实现上述目标?如果该 Web 元素包含我 dont 想要的字符串,则删除它?
  • 好吧,没关系,我想我明白了。我是否要创建另一个包含我不想要的元素的 iList,然后使用第二个 iList 从原始 iList 中删除对象?

标签: c# list selenium-webdriver


【解决方案1】:

并非所有实现 IList 的东西都是可编辑的。最简单的解决方案是使用 Linq 构建一个过滤器并对其执行 ToList()。

    IList<IWebElement> tableRows;
    tableRows = FindElement(By.XPath("//div[@ui-grid='vm.gridWoodSmokeViolations']")).FindElements(By.XPath("//div[@role='row']"));

    Console.WriteLine("table row count before loop: " + tableRows.Count);

    tableRows = tableRows.Where(row=> !row.Text.ToString().Contains("WSC")).ToList();

【讨论】:

  • 哇,这正是我所需要的。谢谢@斯科特张伯伦
  • @kevin 如果正确回答了您的问题,请确保将答案设为已接受。
  • @JohnM.Wright 很抱歉我已经标记了它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多