How can I access a element of a IReadOnlyCollection through it index?

情到浓时终转凉″ 提交于 2020-05-25 09:49:20

问题


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


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/32638728/how-can-i-access-a-element-of-a-ireadonlycollection-through-it-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!