简体   繁体   English

检查该值是否存在于下拉列表中

[英]Check if the value exists in a dropdown

I have a dropdown that contains Subjects. 我有一个包含主题的下拉菜单。

What I did, I use the code below to get the values on that dropdown. 我所做的是,我使用下面的代码来获取该下拉列表中的值。

IList<IWebElement> allOptions = check.Options;

Then I declare a string that will handle all the values I have to verify if these values exist on that dropdown. 然后,我声明一个字符串,该字符串将处理所有我必须验证的值,以确保这些值在该下拉列表中是否存在。

string[] subject = "Math", "Science", "History", "Calculus", etc...

I loop them to get how many subjects I have to check if they exist on the dropdown then verify it using Contains. 我将它们循环以获取要检查的主题数,然后使用“包含”进行验证。

if (allOptions.Contains(subject[i]))
                {
                    exist = true;
                }

However, I am getting an error that cannot convert a string to OpenQA.Selenium.IWebElement. 但是,我收到一个错误,无法将字符串转换为OpenQA.Selenium.IWebElement。

Anyone has idea how to fix it? 有人知道如何解决吗?

Thank you. 谢谢。

You can use LINQ for this. 您可以为此使用LINQ。 Basically this code: 基本上这段代码:

if (allOptions.Contains(subject[i]))
{
    exist = true;
}

Can be replaced by a single line: 可以用单行替换:

exist = allOptions.Any(x => x.Text == subject[i]);

Basically this code just checks if any element in the allOptions list has Text that matches subject[i] . 基本上,这段代码只是检查allOptions列表中的任何元素是否具有与subject[i]匹配的Text If true, exist is now true , if false exist is now false . 如果为true,则existtrue ,如果为false exist则now为false

Indeed, you cannot do that directly. 确实,您不能直接这样做。 The IWebElement contains a string property named Text , which is what you need to filter on. IWebElement包含一个名为Textstring属性,您需要对其进行过滤。 Like so: 像这样:

var foundSubjects = allOptions.Where(o => subject.Contains(o.Text)); 

If you just need to find out if ALL the options are found in the subject array, do: 如果仅需要查找是否在subject数组中找到了所有选项,请执行以下操作:

var optionsAreValid = allOptions.All(o => subject.Contains(o.Text)); 

Alternatively you could use Any to determine if at least one option exists in the subject array: 或者,您可以使用Any来确定subject数组中是否至少存在一个选项:

var isThereAValidOption = allOptions.All(o => subject.Contains(o.Text)); 

Use the Text property of the WebElement . 使用WebElementText property it may be work for you 可能对你有用

Try looping through the IList<IWebElement> instead: 尝试遍历IList<IWebElement>

int subjectCount = 0;

foreach (IWebElement element in allOptions)
{
    if (subject.Contains(element.Text))
    {
        subjectCount++;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM