Reputation: 21280
I have the following code:
foreach(string reelid in unValidatedFeedersOnMachine.Keys)
{
_sqlString.Append("CompID = '").Append(reelid).Append("' ");
}
I need to add in that loop on each iteration .Appened("or ")
except the last one.
Any idea how i can know when i located on the last iteration here?
Upvotes: 2
Views: 103
Reputation: 1063559
I would do it the other way around - treating the first as the exception is simpler:
bool first = true;
foreach(string reelid in unValidatedFeedersOnMachine.Keys)
{
if(first) {first = false;}
else {_sqlString.Append(" or ";}
_sqlString.Append("CompID = '").Append(reelid).Append("' ");
}
or in .NET 4.0 just use:
string s = string.Join(" or ",
from key in unValidatedFeedersOnMachine.Keys
select "CompID = '" + reelid + "'");
or even better, if this is SQL - switch to IN
...
string s = "CompID IN (" + string.Join(","
from key in unValidatedFeedersOnMachine.Keys
select "'" + reelid + "'") + ")";
Upvotes: 5
Reputation: 6765
I tend to do this
var _sqlString = new StringBuilder();
foreach(string reelid in unValidatedFeedersOnMachine.Keys) {
if(_sqlString.ToString().Length != 0) {
_sqlString.Appened(" or ")
}
_sqlString.Append("CompID = '").Append(reelid).Append("' ");
}
Upvotes: 0
Reputation: 57220
What about doing all in one line ?
string query = string.Join(" or ", unValidatedFeedersOnMachine.Keys.Select(x => "CompID = '" + x + "'").ToArray())
P.S.
If you're targeting .net 4.0, you can skip the .ToArray()
Upvotes: 4