Question

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?

Was it helpful?

Solution

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 + "'") + ")";

OTHER TIPS

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()

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("' ");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top