26

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

4

2 回答 2

39

将 ElementAt(int) 函数与索引值一起使用。

这是 ElementAt(int) 函数的 MSDN 链接https://msdn.microsoft.com/en-us/library/bb299233(v=vs.110).aspx

于 2015-09-17T19:55:02.720 回答
15

我没有使用只读集合,但是从MSDN文档中,看起来可以使用ElementAt方法获取给定索引处的元素。它应该像这样工作:

IReadOnlyCollection<IWebElement> rows = Driver.FindElements(By.XPath("./*/tr"));   

int index = 1; // sample

var row = rows.ElementAt(index)

您可能需要using System.Linq;在您的类中添加语句,因为ElementAt()是 Linq 提供的扩展方法。

于 2015-09-17T19:56:03.960 回答