I am working with selenium and I am using the function FindElements so I am getting a element that implements IReadOnlyCollection interface. I want to iterate through the list but it seems that IReadOnlyCollection doesnt have any method like Get(int index) or a implementation of the operation [].
I want to avoid transforming the result to a List or to an array since I just want to access the elements to read them.
Currently I don't want to use a foreach since I need to manage an index so I can add those elements to an 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
The IReadOnlyCollection interface extends the IEnumerable interface and represents a basic read-only collection interface. It also includes a Count property apart from the IEnumerable members as shown in the code snippet given below.
List<T> can be cast as IReadOnlyList<T> so you don't have to change anything else inside your method. You can create a List<GuitarItems> just as you are now, but return it as an IReadOnlyList<GuitarItems> just by changing the return type of the function. That probably accomplishes what you need.
That said, you can use the following: IReadOnlyCollection<TValue> readonlyCollection = new ReadOnlyCollection<TValue>(new TValue[] { }); Optionally you can cache the results as it is a ReadOnlyCollection over empty array, It will always be the same no matter how many instances you have.
The fact that ReadOnlyCollection is immutable means that the collection cannot be modified, i.e. no objects can be added or removed from the collection.
Use the ElementAt(int) function with the index value.
Here is the MSDN link to the ElementAt(int) function https://msdn.microsoft.com/en-us/library/bb299233(v=vs.110).aspx
I haven't been using read only collections, but from the MSDN documentation, it looks like it's possible to get element at given index, using ElementAt
method. It should work like that:
IReadOnlyCollection<IWebElement> rows = Driver.FindElements(By.XPath("./*/tr")); int index = 1; // sample var row = rows.ElementAt(index)
You might need to add using System.Linq;
statement in your class, because ElementAt()
is an extension method provided by Linq.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With