Convert foreach loop to Linq code
Converting this code to Linq:
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…
}
}
}
Linq:
foreach (string match in selections.Where(match => checkboxName == match.Trim()))
{
//matched… do more work here…
}
or
If your selections list contains only distinct values, than you could use
if(selections.Any(match=>match.Trim().Equals(checkboxName)))
{
//Do work
}
or
You also use method ToList to change to ForEach linq:
selections.Where(match => checkboxName == match.Trim())
.ToList()
.ForEach(match => {
//matched… do more work here…
});
Refactoring horrible nested if-else statements Extract substring from a string until finds a comma c# asp.net