2017-09-13 254 views
1

運行以下代碼片段時,我收到了異常。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 

      } 

     } 

感謝所有幫助您可以提供

+0

不要在使用'foreach'循環它時修改集合。嘗試使用'for'循環,就像[在這個答案中](https://stackoverflow.com/questions/7340757/c-sharp-list-removing-items-while-looping-iterating)。或者找到要移除的項目,保存對其的引用(LINQ可以在這裏獲得幫助),然後在循環之後移除它。 – Jonesopolis

+0

@Jonesopolis我將如何實現上述目標?刪除那個Web元素,如果它包含字符串我*不*想要? – kevin

+0

好吧,沒關係,我想我明白了。我是否創建另一個包含我不想要的元素的iList,然後使用第二個iList從原始iList中刪除對象 ? – kevin

回答

3

不是說implments 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(); 
+0

哦哇,這正是我需要的。謝謝@Scott Chamberlain – kevin

+0

@kevin如果能正確回答你的問題,請確保答案被接受。 –

+0

@ JohnM.Wright對於我已經標記過的想法感到抱歉 – kevin

相關問題