5
\$\begingroup\$

I need to click on a "account" button from a table of buttons. If this "account" button is not present, then I will need to click a different "UseAnotherAccount" button.

How I do it at the moment is:

  • Set a flag account_found to be false by default
  • use a foreach loop to search through the whole _list of buttons
  • If the expected account button is found, click it, set account_found flag to be true and break away from this foreach loop
  • an additional if block is used to to click on UseAnotherAccount button if account_found flag is not set.

My code is shown below:

bool account_found = false;
foreach (DivTag element in _list) {
    String account_name = element.GetInnerHtml();
    if (account_name.Equals(_account_name)) {
        element.Click();
        account_found = true;
        break;
    }
}
if (!account_found) {
    _my_repo.SignInToYourAccount.UseAnotherAccount.Click();
}

I have this feeling my way is not the most elegant way to achieve this. Any suggestions?

\$\endgroup\$
2
  • \$\begingroup\$ I assume that this question involves code for selenium? \$\endgroup\$ Commented Jan 10, 2018 at 1:02
  • \$\begingroup\$ @200_success, not really, it was developed for Ranorex platform. But in principle, we could interpret the code as if it was written in Selenium, basically same purpose. \$\endgroup\$ Commented Jan 10, 2018 at 5:56

1 Answer 1

4
\$\begingroup\$

To eliminate the need for the flag you could do it like this:

var element = _my_repo.SignInToYourAccount.UseAnotherAccount;
foreach (var item in _list)
{
    if (item.GetInnerHtml().Equals(_account_name))
    {
        element = item;
        break;
    }
}
element.Click();

However, your code can be greatly simplified with the Linq extension methods provided in the System.Linqnamespace:

var element = _list.FirstOrDefault(x => x.GetInnerHtml().Equals(_account_name)) ?? _my_repo.SignInToYourAccount.UseAnotherAccount;
element.Click();
\$\endgroup\$
0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.