C# 将foreach循环转换为linq代码
下面的代码按预期工作,但我希望将下面的代码转换为使用Linq? 有什么建议吗C# 将foreach循环转换为linq代码,c#,linq,C#,Linq,下面的代码按预期工作,但我希望将下面的代码转换为使用Linq? 有什么建议吗 string[] selections = "Men,Women,Boys".Split(','); int _chkboxId = 0; int _chkboxTextId = 1; try { string id = "lstchk_" + _chkboxId;
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...
}
}
}
有时,编写代码的方法不同。如果您的
选择
列表仅包含不同的值,则无法使用
if(selections.Any(match=>match.Trim().Equals(checkboxName)))
{
//Do work
}
而不是你的循环。如果您的列表可能包含非不同的值,则相同,但每个
checkboxName
只能执行一次,您如何将这个简单的foreach转换为linq语句
public List<string> GetItems()
{
var items = new List<string>();
foreach (Ranorex.ListItem item in ranorexComboBox.Items)
{
items.Add(item.Text);
}
return items;
}
公共列表GetItems()
{
var items=新列表();
foreach(ranorexComboBox.Items中的Ranorex.ListItem项)
{
items.Add(item.Text);
}
退货项目;
}
匹配的//。。。在这里做更多的工作…
这一部分实际上很重要,根据您在那里要做的事情,您可以用不同的方式表达您的Linq
if(selections.Any(match=>match.Trim().Equals(checkboxName)))
{
//Do work
}
public List<string> GetItems()
{
var items = new List<string>();
foreach (Ranorex.ListItem item in ranorexComboBox.Items)
{
items.Add(item.Text);
}
return items;
}