I have a collection of objects that I would like to iterate through to ultimately recognize some type of pattern. Currently I have a bunch of if statements that checks a flag for the expression. For example I have something along the lines of if (!foundFirstObjectOfTypeA). Once I found the first object of type A I would set the flag to true and we would no longer execute the block and move on to the next block. I have several types of patterns to recognize and because of this it has created a large block of if statements that are hard to understand and ugly.
Is there a way to peek/look past the identifier without the evaluation of the expression in the foreach loop? If I could do something along the lines of if (identifer == ObjectA && identifer.next == ObjectB) it would make my code much more readable and understandable and I could deal without having to set flags.
If there is no direct method/way does someone have some clever workarounds to simulate the effects I desire?
Use a
forloop instead to incrementi, then just look atobject[i]andobject[i+1]. What type of collection are you using? A list? An array? All aforeachloop does is hide the counter from you. There’s absolutely no reason to use aforeachloop instead of aforloop, if I understand your situation.This should work for any list and any sequence of objects:
Function:
Usage:
Output:
The function can be made simpler if you know how many objects you’re looking for (if you’re only looking for two, it’s almost Hamid Nazari‘s answer – you just need to add AndrewS‘s bound checking, below.)
If you want the index of the start of the sequence, you can change the return type of my function to an int and return
iinstead oftrue(and return-1instead offalse.)