運行以下代碼片段時,我收到了異常。System.NotSupportedException:'集合是隻讀的。'從iList中刪除對象時拋出
我有一個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'循環,就像[在這個答案中](https://stackoverflow.com/questions/7340757/c-sharp-list-removing-items-while-looping-iterating)。或者找到要移除的項目,保存對其的引用(LINQ可以在這裏獲得幫助),然後在循環之後移除它。 – Jonesopolis
@Jonesopolis我將如何實現上述目標?刪除那個Web元素,如果它包含字符串我*不*想要? – kevin
好吧,沒關係,我想我明白了。我是否創建另一個包含我不想要的元素的iList,然後使用第二個iList從原始iList中刪除對象 ? – kevin