user1499172
user1499172

Reputation:

convert foreach loop to linq code

the below code is working as expected but I'm looking to convert the below code to use Linq? any suggestions?

       string[] selections = "Men,Women,Boys".Split(',');           

        int _chkboxId = 0;  
        int _chkboxTextId = 1;
        try
        {
            string id = "lstchk_" + _chkboxId;
            while (!driver.FindElement(By.Id(id)).Equals(null))
            {
                string checkboxId = String.Format("lstchk{0}", _chkboxTextId);
                string checkboxName = driver.FindElement(By.Id(checkboxId)).Text;

                foreach (string match in selections)
                {
                    if (checkboxName == match.Trim())
                    {
                        //matched... do more work here...
                    }
                }
           }

Upvotes: 3

Views: 1625

Answers (4)

SwordPhish23
SwordPhish23

Reputation: 11

How would you convert this simple foreach to a linq statement?

    public List<string> GetItems()
        {
        var items = new List<string>();

        foreach (Ranorex.ListItem item in ranorexComboBox.Items)
            {
            items.Add(item.Text);
            }

        return items;
        }

Upvotes: 0

horgh
horgh

Reputation: 18553

If your selections list contains only distinct values, than you could use

if(selections.Any(match=>match.Trim().Equals(checkboxName)))
{
    //Do work
}

instead of your loop. Same if your list may contain non-distinct values, but the work should be done only once for each checkboxName

Upvotes: 1

nneonneo
nneonneo

Reputation: 179687

switch(checkboxName) {
    case "Men":
    case "Women":
    case "Boys":
        // do more work here
    default:
        // no match, bail
}

Sometimes, there's just a different way to write the code.

Upvotes: 1

Ofer Zelig
Ofer Zelig

Reputation: 17508

foreach (string match in selections.Where(match => checkboxName == match.Trim()))
{
    //matched... do more work here...
}

Upvotes: 5

Related Questions