0

I have a for loop to print a sets of addresses. But i want to do a condition where it skip printing the set of address that has the same value as postalCode-X.

So how to can i escape from a forloop? the language is in C#,.NET framework. thanks.

the DATA look like this:

SET 1 
Street 1
California 1770 

SET 2 
Street 2 
New Jersey 1990 

SET 3 
Street 3 
Oakland 2000

Output with exception of postalcode 1990:

Print SET1 and SET3 only.

foreach (Dataset.Row dr in A.Rows)
        {
            if (dr.id("1"))
            {
                string unit = dr.unit;
                string streetName = dr.street;
                string postalCode = dr.postal;
                content += String.Format("{0}", dr.name);
                if (showAddress)
                    content += "<br/>" + GenAddr(unit,streetName, postalCode) + "<br/>";
            }
        }
  • Thanks for updating your code. Why do you have `if(dr.id("1"))`? I now take it you don't want to print to the console, but you're wanting to write HTML content to the client. What is content? – mason Feb 26 '14 at 03:22
  • hi, dr.id('1') is just an example, it is actually referring to a column with the type of A then go into that if statement. The content will be generated into a word document.is also fine to say it will be a HTML. – user2754476 Feb 26 '14 at 03:38

3 Answers3

2
//inside the loop
if(!currentset.PostalCode.Equals("1990"))
    {
    Console.WriteLine("Set: "+currentset);
    }

A simple if statement does what you want. I could give you an answer more customized for your situation if you would update the question with your loop and what data type the sets are etc.

Note that the above code is not "escaping" the loop. It's just selectively printing out sets from inside the for loop. The code below makes use of the continue statement in C# to "escape" the rest of the code in the loop.

//inside the loop
if(currentset.PostalCode.Equals("1990")
{
    continue; //the curly braces are unnecessary for a single line in the if statement
}
Console.WriteLine("Set: "+currentset); //notice this is after the continue statement

Another option would be to have List and then remove the sets with Linq that you don't want prior to having a loop that prints out the sets.

List<set> sets=GetSets();
set.RemoveAll(aset => aset.PostalCode.Equals("1990"));
//now loop through sets
foreach(set currentset in sets)
{
    Console.WriteLine("Set: "+set);
}
Community
  • 1
  • 1
mason
  • 31,774
  • 10
  • 77
  • 121
1

Or using linq.

yourList.Where(x=>!x.PostalCode.Equals("1990")).ForEach(Console.WriteLine)
shenku
  • 11,969
  • 12
  • 64
  • 118
0

Also you have another way to do:

//inside the loop
if(!currentset.PostalCode.Equals("1990"))
{
    Console.WriteLine("Set: "+currentset);
}

OR

//inside the loop
if(currentset.PostalCode.Equals("1990"))
    continue;
Console.WriteLine("Set: "+currentset);
Chris Shao
  • 8,231
  • 3
  • 39
  • 37