How to break two for loop [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
How to break two for loop at the highlighted line. (after showing the MessageBox.Show("THE ITEM ID DOES NOT EXIST.!"); )
bool conditionitem = true;
for (int cun = 0; cun < ItemIdNumber.Length; cun++)
{
int Item_Id = Convert.ToInt32(ItemIdNumber[cun]);
for (int yyu = 0; yyu <= 1258038; yyu++)
{
int weer = c[yyu];
if (weer == Item_Id)
{
conditionitem = false;
itemseq = yyu;
}
}
if (conditionitem != false)
{
MessageBox.Show("THE ITEM ID DOES NOT EXIST.!");
break; //--> here i want two break for two times
}
}
By this break it only break the first loop.

Two options I can think of:
(1) Set a flag inside the second loop before you break out of it. Follow the inner iteration with a condition that breaks out of the first iteration if the flag is set.
bool flag = false;
foreach (item in Items)
{
foreach (item2 in Items2)
{
flag = true; // whenever you want to break
break;
}
if (flag) break;
}
(2) Use a goto statement.
foreach (item in Items)
{
foreach (item2 in Items2)
{
goto GetMeOutOfHere: // when you want to break out of both
}
}
GetMeOutOfHere:
// do what you want to do.

You can refactor the loop to be a method that finds the item:
SomeType SomeMethod(int itemId)
{
for (int cun = 0; cun < ItemIdNumber.Length; cun++)
{
int Item_Id = Convert.ToInt32(ItemIdNumber[cun]);
for (int yyu = 0; yyu <= 1258038; yyu++)
{
if (c[yyu] == itemId) return yyu;
}
}
return null;
}
Then just use that:
var item = SomeMethod(Item_Id);
if(item == null)
{
MessageBox.Show("THE ITEM ID DOES NOT EXIST.!");
}
else
{
// ...
}
This also avoids mixing UI logic and internal logic.

Put your nested loop into a function and return true/false whenever you want to break the loop?
bool Function()
{
for(int i = 0; i < 10; ++i)
{
for(int j = 0; j < 10; ++j)
{
if (error)
{
MessageBox.Show("THE ITEM ID DOES NOT EXIST.!");
return false;
}
}
}
return true;
}

Related

Skip foreach X positions

I want skip my in foreach. For example:
foreach(Times t in timeList)
{
if(t.Time == 20)
{
timeList.Skip(3);
}
}
I want "jump" 3 positions in my list.. If, in my if block t.Id = 10 after skip I want get t.Id = 13
How about this? If you use a for loop then you can just step the index forward as needed:
for (var x = 0; x < timeList.Length; x++)
{
if (timeList[x].Time == 20)
{
// option 1
x += 2; // 'x++' in the for loop will +1,
// we are adding +2 more to make it 3?
// option 2
// x += 3; // just add 3!
}
}
You can't modify an enumerable in-flight, as it were, like you could the index of a for loop; you must account for it up front. Fortunately there are several way to do this.
Here's one:
foreach(Times t in timeList.Where(t => t.Time < 20 || t.Time > 22))
{
}
There's also the .Skip() option, but to use it you must break the list into two separate enumerables and then rejoin them:
var times1 = timeList.TakeWhile(t => t.Time != 20);
var times2 = timeList.SkipeWhile(t => t.Time != 20).Skip(3);
foreach(var t in times1.Concat(times2))
{
}
But that's not exactly efficient, as it requires iterating over the first part of the sequence twice (and won't work at all for Read Once -style sequences). To fix this, you can make a custom enumerator:
public static IEnumerable<T> SkipAt<T>(this IEnumerable<T> items, Predicate<T> SkipTrigger, int SkipCount)
{
bool triggered = false;
int SkipsRemaining = 0;
var e = items.GetEnumerator();
while (e.MoveNext())
{
if (!triggered && SkipTrigger(e.Current))
{
triggered = true;
SkipsRemaining = SkipCount;
}
if (triggered)
{
SkipsRemaining--;
if (SkipsRemaining == 0) triggered = false;
}
else
{
yield return e.Current;
}
}
}
Then you could use it like this:
foreach(Times t in timeList.SkipAt(t => t.Times == 20, 3))
{
}
But again: you still need to decide about this up front, rather than inside the loop body.
For fun, I felt like adding an overload that uses another predicate to tell the enumerator when to resume:
public static IEnumerable<T> SkipAt<T>(this IEnumerable<T> items, Predicate<T> SkipTrigger, Predicate<T> ResumeTrigger)
{
bool triggered = false;
var e = items.GetEnumerator();
while (e.MoveNext())
{
if (!triggered && SkipTrigger(e.Current))
{
triggered = true;
}
if (triggered)
{
if (ResumeTrigger(e.Current)) triggered = false;
}
else
{
yield return e.Current;
}
}
}
You can use continue with some simple variables.
int skipCount = 0;
bool skip = false;
foreach (var x in myList)
{
if (skipCount == 3)
{
skip = false;
skipCount = 0;
}
if (x.time == 20)
{
skip = true;
skipCount = 0;
}
if (skip)
{
skipCount++;
continue;
}
// here you do whatever you don't want to skip
}
Or if you can use a for-loop, increase the index like this:
for (int i = 0; i < times.Count)
{
if (times[i].time == 20)
{
i += 2; // 2 + 1 loop increment
continue;
}
// here you do whatever you don't want to skip
}

Why is List<T>.Add method not working in the specific if/else block? (C#) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I have an Infint class with one List field. In the main program, I want to read numbers (character by character) and add them to this list.
The assignment itself doesn't matter in this moment, what I'm wondering is why I can't add values to the list of the Infint object from the if/else block (inside the first while loop). I have initialised the List itself in the class constructor. I added the line number1.Number.Add(1) for debugging reasons, since the code wasn't working and I've come to realize it seems to be working fine outside that if/else block. I can't seem to find the solution.
Here are the following implementations:
internal class Infint
{
public bool isNegative { get; set; }
public List<int> Number { get; set; }
public Infint()
{
isNegative = false;
Number = new List<int>();
}
}
static void Main(string[] args)
{
using (StreamReader sr = new StreamReader("infint.txt"))
{
int i;
char num;
for (int operation = 0; operation < 3; operation++)
{
Infint number1 = new Infint();
Infint number2 = new Infint();
number1.Number.Add(1); //works
i = sr.Read();
while (sr.Peek() >= 0)
{
number1.Number.Add(1); //works
if (i == 10 || i == 13)
break;
num = (char)i;
if (operation == 0)
{
number1.Number.Add(1); //doesn't work
if (i == 45)
number1.isNegative = true;
else
{
number1.Number.Add(1); //doesn't work
//number1.Number.Add((int)Char.GetNumericValue(num));
}
}else if(operation == 1)
{
if (i == 45)
number2.isNegative = true;
else
{
number2.Number.Add((int)Char.GetNumericValue(num));
}
}else if(operation == 2)
{
Console.WriteLine("counts of num1: " + number1.Number.Count);
for (var k = 0; k < number1.Number.Count; k++)
{
Console.Write(number1.Number[k]);
}
Console.WriteLine("counts of num2: " + number2.Number.Count);
for (var k = 0; k < number2.Number.Count; k++)
{
Console.Write(number2.Number[k]);
}
}
i = sr.Read();
}
if (i == -1)
{
break;
}
//i = sr.Read();
}
}
Console.Read();
}
Removing the various noise in your code (it's extremely low quality, if you care), what you're left with is:
using var sr = new StreamReader("infint.txt");
for (int operation = 0; operation < 3; operation++)
{
var i = sr.Read();
while (sr.Peek() >= 0)
{
if (i == 10 || i == 13) break;
if (operation == 0)
{
// oh noes
}
}
}
So looking at the code and assuming what you describe is correct (if vague), that means that your text file starts with a new line, possibly two (you don't even mention your OS, let alone the contents of the file). If that is indeed the case, then it should be strikingly obvious why operation can't be 0 around the branch you're expecting it to be.

How to pause a for loop until the enter key is pressed? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
for example
bool x = false;
if(press enter)
{
x = true;
}
for(int i = 0; i < 10; i++)
{
if(x == true)
print (i);
x = false;
}
code like that always give me 0 after enter pressed instead of the whole sequence 1,2,3...10.
I found three answer online, but all of them are not wrote in c#, I actually use it in Unity, so it has to be c#..
for(int i = 0; i < 10; i++)
{
if(x == true)
print(i);
// This line is executed allways
x = false;
}
So what happens is that
in the first call x == true so it prints 0.
Then it sets x = false
In future iteration x == false => so no more output.
You probably wanted something like
// only check this once since it isn't changed in the loop
// do not loop at all if button wasn't pressed
if(x)
{
// Do all prints in a loop
for(int i = 0; i < 10; i++)
{
print(i); // prints 0 1 2 3 4 5 6 7 8 9
}
// reset the flag so you do the printing only in the frame
// where the button was pressed
x = false;
}
And for Unity specific you might want to use Input.GetKeyDown instead of x.
You can run your for loop during the frame that the return key is released. This ensures that we don't run this for every frame that the key is down (I'm assuming you don't want that). To do this we just check with Input.GetKeyUp which returns a boolean when the specified key is released.
if(Input.GetKeyUp(KeyCode.Return))
{
for(int i = 0; i < 10; i++)
print(i);
}
You can use Coroutine with Input.GetKeyDown and then do yield return.
For Example:
private bool _pause = false;
private void Start()
{
StartCoroutine(FuncName());
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Return))
{
_pause = !_pause;
}
}
private IEnumerator FuncName()
{
for(int i = 0; i < 10; i++)
{
while (_pause)
{
yield return null;
print (i);
}
}
}

C#: Code review for 'Contine' in catch block inside for-loop [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
Following is my code,where I need to continue the loop in case of exception inside try block.
for (int i = 0; i < doc.Length; i++)
{
name = doc[i].ToString();
try
{
if (name != "")
{
name=name.ToString().Substring(12);
break;
}
}
catch{
continue;
}
}
Please tell me if i`m wrong at any place in my code.Please check for performance wise too.
Thanks in advance.
The continue is unneeded. It will automatically continue.
var name = doc.FirstOrDefault(x => !string.IsNullOrEmpty(x) && x.Length >= 12);
You don't need exception handling if you can avoid it:
for (int i = 0; i < doc.Length; i++)
{
name = doc[i].ToString();
if(name != null && name.Length >= 12)
{
name = name.Substring(12);
break;
}
}
Never use exceptions for something that is not exceptional. If you don't expect any of documents will have length less that 12, then you can use exceptions (but also not just for control flow):
for (int i = 0; i < doc.Length; i++)
{
name = doc[i].ToString();
if (name.Length < 12)
throw new FooException("Wrong document found!");
// do something with name
}
You do not need break or continue here.
try this.
for (int i = 0; i < doc.Length; i++)
{
name = doc[i].ToString();
try
{
if (!string.IsNotNullOrEmpty(name))
{
name=name.ToString().Substring(12);
}
}
catch{ }
}

Break foreach loop (WCF server/client)

I have a simple code, which send from server to clients value to count. This loop count for 9 value, from 1 to 9. Everything work good for 1,3 or 9 clients. But for other number of clients when i_wiersz has value 9 and foreach loop want sent something to another client server break down. Ho make, to work with any one numbers of clients?
I try put inside foreach loop:
if(i_wiersz == 9)
break;
but a get an error: Error
Control cannot leave the body of an anonymous method or lambda
expression
My code:
bool spr_wiersz(int wiersz, int kolumna) //chck_roow(int roow, int column)
{
wys_tab();
int i_wiersz = 0;
bool[] result = new bool[9];
while (i_wiersz < 9)
{
subscribers.ForEach(delegate(ImessageCallback callback)
{
if (((ICommunicationObject)callback).State == CommunicationState.Opened)
{
result[i_wiersz] = callback.spr_wiersz(wiersz, kolumna, i_wiersz);
i_wiersz++;
}
});
for (int j = 0; j < i_wiersz; j++)
{
if (result[j] == false)
{
return false;
}
}
}
return true;
}
Can’t you simply convert it to a traditional foreach?
foreach (IMessageCallback callback in subscribers)
{
if (((ICommunicationObject)callback).State == CommunicationState.Opened)
{
result[i_wiersz] = callback.spr_wiersz(wiersz, kolumna, i_wiersz);
i_wiersz++;
if (i_wiersz == 9)
break;
}
}

Categories

Resources