How to write the same piece of code in C# ?
List<WebElement> displayedOptions = driver.FindElements(By.TagName("select"));
for (WebElement option : displayedOptions)
{
if (option.displayed)
{
displayedOptions.Add(option);
}
}
There is a class created specifically for select
HTML elements (i.e. dropdowns).
It is the SelectElement class inside the OpenQA.Selenium.Support.UI namespace.
This is a wrapper around select
elements, giving easy access to common things people use/interact with in select
elements.
Your example would be translated into (using C# 3 or above, since I'm using LINQ):
IList<IWebElement> selectElements = driver.FindElements(By.TagName("select"));
var displayedSelectElements = selectElements.Where(se => se.Displayed);
It's important to know what this code does. It will first find all select
elements and put them into a new list.
It will then filter those out, to only the select
elements that are displayed, that is, their .Displayed
property is true. This is a direct translation of your example code.
However, you've not really specified what you are trying to do, and I think the example is better suited as this:
var selectElement = new SelectElement(driver.FindElement(By.Id("something")));
var displayedOptions = selectElement.Options.Where(o => o.Displayed);
The above would find a specific select
elements, and filter the options within that select
to only those that are displayed. Again, that is, have their .Displayed
property as true.
Edit
Since the above code is what you need, but you want in the form of a for
loop, a similar thing would look like:
var selectElement = new SelectElement(driver.FindElement(By.Id("something")));
var allOptions = selectElement.Options;
for (int i = 0; i < allOptions.Length; i++)
{
if (allOptions[i].Displayed)
{
// do something
// like add to a new list?
}
}
FindElements returns ReadOnlyCollection. So its better to define
ReadOnlyCollection<IWebElement> displayedOptions = driver.FindElements(By.TagName("select"));
for (WebElement option : displayedOptions)
{
if (option.displayed)
{
//displayedOptions.Add(option); //You can't do that
// do something else
}
}
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