Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 331
  • Last Modified:

Syntax for While(Condition1 or Condition2)

I have a while loop that should continue while either condition 1 or condition 2 is true.

Condition 1: ((intLinesProcessed) <= intMaxtoProcess)  // Lines processed are less than the max lines to process.  
Condition 2:  sr.ReadLine()) != null) // Reads to the eof

while ((intLinesProcessed) <= intMaxtoProcess)  ||  (sr.ReadLine()) != null)

What is the proper syntax?

Thanks,
0
Dovberman
Asked:
Dovberman
1 Solution
 
DontmilkthisCommented:
I think your code is almost syntactically correct, although you've got an extra parenthesis. also you don't strictly need them around each condition

while (intLinesProcessed <= intMaxtoProcess  ||  sr.ReadLine() != null) 
{
  //do stuff
  intLinesProcessed++;
}

Open in new window


also, by using the ReadLine in the if clause, you're consuming a line from the stream reader. if you want to use the line it should be set to a variable.

so i'd change the second condition to use the end of stream flag, so you can actually do stuff with the line

while (intLinesProcessed <= intMaxtoProcess  || !sr.EndOfStream) 
{
  line = sr.ReadLine();
  //do stuff
  intLinesProcessed++;
}

Open in new window


This will still cause a problem where you've set intMaxtoProcess to a higher number than the actual number of lines.
eg:
intMaxtoProcess = 10
intLinesProcess = 2

your condition will resolve to true and will try to execute, when it attempts a ReadLine it will throw an exception.

I think what you really want is an AND not an OR. this way, your loop will execute until you've processed the desired amount of lines, or you've reached the end of the stream.

while (intLinesProcessed <= intMaxtoProcess  && !sr.EndOfStream) 
{
  line = sr.ReadLine();
  //do stuff
  intLinesProcessed++;
}

Open in new window

0
 
DovbermanAuthor Commented:
Thank you for the complete detailed description.
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now