How can I access an IReadOnlyCollection element through its index?

I work with selenium and I use the FindElements function, so I get an element that implements the IReadOnlyCollection interface. I want to iterate over the list, but it seems that IReadOnlyCollection has no method, for example Get (int index) or implementation of operation [].

I want to avoid converting the result to a list or array, since I just want to access the elements to read them.

Currently, I do not want to use foreach, since I need to manage the index, so I can add these elements to another array.

This is what I want to do:

public void fillMatrix(){ IReadOnlyCollection<IWebElement> rows = Driver.FindElements(By.XPath("./*/tr")); IReadOnlyCollection<IWebElement> elements; matrix = new IControl[rows.Count()][]; for(int i = 0; i < matrix.Count(); ++i){ matrix[i] = rows[i].FinElements("./td").toArray(); } } 

thanks

+5
source share
2 answers

Use the ElementAt (int) function with an index.

Here is the MSDN link to the ElementAt (int) function https://msdn.microsoft.com/en-us/library/bb299233(v=vs.110).aspx

+9
source

I have not used read-only collections, but from the MSDN documentation, it looks like you can get an element at a given index using the ElementAt method. It should work as follows:

 IReadOnlyCollection<IWebElement> rows = Driver.FindElements(By.XPath("./*/tr")); int index = 1; // sample var row = rows.ElementAt(index) 

You may need to add a statement using System.Linq; to its class, because ElementAt() is an extension method provided by Linq.

+7
source

All Articles