2

I'm getting an exception thrown when running the snippet of code below.

I have an iListof webelements, and if that element contains the string "WSC", I'd like to remove it from the iList.

Can anyone help me out? Code below.

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

            }

        }

Thanks for any help you may be able to provide

kevin
  • 37
  • 5
  • 21
  • Don't modify a collection when looping through it using a `foreach`. Try using a `for` loop like [in this answer](https://stackoverflow.com/questions/7340757/c-sharp-list-removing-items-while-looping-iterating). Or find the item to remove, save a reference to it (LINQ can help here) and then remove it *after* the loop. – Jonesopolis Sep 13 '17 at 01:28
  • @Jonesopolis how would i achieve my goals mentioned above? removing that web element if it contains the string i *dont* want? – kevin Sep 13 '17 at 01:30
  • ok nevermind i think i got it. do i create another iList that contains the elements i don't want, then use that 2nd iList to remove the objects from the original iList? – kevin Sep 13 '17 at 01:32
  • Possible duplicate of [c# why System.Array class implements IList but does not provide Add()](https://stackoverflow.com/questions/38117870/c-sharp-why-system-array-class-implements-ilist-but-does-not-provide-add) – mjwills Sep 13 '17 at 03:46

1 Answers1

3

Not all things that implments IList are editable. The easiest solution is just use Linq to build a filter and do a ToList() on it.

    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();
Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431