我有以下代码:
foreach(string reelid in unValidatedFeedersOnMachine.Keys)
{
_sqlString.Append("CompID = '").Append(reelid).Append("' ");
}
我需要在每次迭代 .Appened("or ")
中添加该循环,但最后一次除外。
知道如何知道我何时位于此处的最后一次迭代吗?
最佳答案
我会反其道而行之 - 将第一个视为异常更简单:
bool first = true;
foreach(string reelid in unValidatedFeedersOnMachine.Keys)
{
if(first) {first = false;}
else {_sqlString.Append(" or ";}
_sqlString.Append("CompID = '").Append(reelid).Append("' ");
}
或者在 .NET 4.0 中使用:
string s = string.Join(" or ",
from key in unValidatedFeedersOnMachine.Keys
select "CompID = '" + reelid + "'");
或者更好,如果这是 SQL - 切换到 IN
...
string s = "CompID IN (" + string.Join(","
from key in unValidatedFeedersOnMachine.Keys
select "'" + reelid + "'") + ")";
关于c# - 是否可以在迭代 ICollection 时确定当前位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4710995/