[英]convert foreach loop to linq code
下面的代碼按預期工作,但我想轉換下面的代碼使用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...
}
}
}
foreach (string match in selections.Where(match => checkboxName == match.Trim()))
{
//matched... do more work here...
}
switch(checkboxName) {
case "Men":
case "Women":
case "Boys":
// do more work here
default:
// no match, bail
}
有時,編寫代碼的方式不同。
如果您的selections
列表僅包含不同的值,則可以使用
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.