简体   繁体   中英

Statements in the Condition of a While Loop

Say I have a collection of things that can be accessed with TheCollection.GetByID(long) , but there's no way for me to get the length of the thing in advance. I'd like to set up a while loop to go through each one.

Clearly I could do something like this:

var iter = 0; var thing = TheCollection.GetByID(iter);
while (thing != null) {
    dealWithTheThing(thing);
    iter++;
    thing = TheCollection.GetByID(iter);
}

But I'd prefer to tidy it up by putting the modifications in the constructor, and be able to get something like this:

var iter = 0; var thing;
while ((thing = TheCollection.GetByID(iter++)) != null) {
    dealWithTheThing(thing);
}

Is this, or something like it, possible?

Yes, your example is fine. You can have assignments within a condition, and the style is perfectly clear (at least to me).

While using the assignment operator in the condition for a loop looks pretty, it can be cause confusion for others as it is easy to typo the == to = ( read more: search for "Assignment Expressions" )

Having given you the warning, I find the following more readable:

 
 
 
 
  
  
  var iter = 0; var thing; while (thing = TheCollection.GetByID(iter++) && thing != null) { dealWithTheThing(thing); }
 
 
  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM