2

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?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Night Walker
  • 20,638
  • 52
  • 151
  • 228
  • Minor note; if each key (`reelid`) is known to be a safe value (from private config data etc) then this may be fine - but **do not** use concatenation if there is *any chance* a user could have influenced them - perhaps by editing the HTML of a FORM. Otherwise this is a SQL injection attack risk. – Marc Gravell Jan 17 '11 at 07:58
  • @ Marc Gravell:Those values come from automatic machine , no chance that someone can influence the values . – Night Walker Jan 17 '11 at 08:02

3 Answers3

5

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 + "'") + ")";
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • (note that I'm assuming in the above that the `reelid` is injection-safe - i.e. it is coming from a trusted source; that may be an invalid assumption) – Marc Gravell Jan 17 '11 at 07:56
4

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

digEmAll
  • 56,430
  • 9
  • 115
  • 140
  • 1
    @Night Walker: well, then unfortunately this code is not so useful in your case. BTW, you should say/tag your question to indicate you're in .net 2.0, because it's becoming somewhat infrequent as requirement... – digEmAll Jan 17 '11 at 07:59
0

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("' ");
}
djeeg
  • 6,685
  • 3
  • 25
  • 28