I have looked into this some, and I can't find a good way to do this. I have functional code but I want to clean it up without using manual counting or breaks. I looked at LINQs TakeWhile function, but that is insufficient in this case. Here is an example of a working implementation of a functional equivalent:
bool foo(List<strings> stringList, int counter)//assume this list has, like, 10 elements, and counter=3, idk
{
...
bool found= false;
for(int i=0; i<stringList.Count && !found; i++)
{
if(stringlist[i].length < 2 || counter >=6)
found=true;
counter++;
}
...
return found
}
And I want to replace it with some "magic" function like this:
bool foo(List<strings> stringList, int counter)//assume this list has, like, 10 elements, and counter=3, idk
{
...
bool found= false;
foreachwhile(string s in stringList while !found)
{
if(s.length < 2 || counter >=6)
found=true;
counter++;
}
...
return found
}
Is there some function that can do this already, and if not how can I write one in C#... or get close? I often find I need to do this, and yes, I know that:
bool foo(List<strings> stringList, int counter)//assume this list has, like, 10 elements, and counter=3, idk
{
...
bool found= false;
foreach(string s in stringList)
{
if(found)
break;
if(s.length < 2 || counter >=6)
found=true;
counter++;
}
...
return found
}
technically works too, but I would like to avoid breaks in my code. Is there any other clean way to accomplish this in c#?
EDIT: I am seeing a lot of confusion about what I am asking here. I would prefer a way to add a very clear check if we should break to the foreach statement itself if possible, or a way to write my own version of foreach
that accepts a parameter that only continues while a condition is true, such as the path isn't found yet.
Also, I am sorry for not being clear, but the biggest reason I want to avoid break is so that I am not jumping out of the loop at an arbitrary point. In this respect return is just as undesirable.
I also have nothing against Linq, I tried to use it, but I found it does not produce the functionality that I am looking for:
bool foo(List<strings> stringList, int counter)//assume this list has, like, 10 elements, and counter=3, idk
{
bool found= false;
foreach(string s in stringlist.Takewhile(x=> (!found)))
{
if(s.length < 2 || counter >=6)
found=true;
counter++;
}
return found
}
is different logic from the above because TakeWhile
executes first and returns an empty set causing the foreach
loop to have nothing to loop over. If someone has another way to write this, I would genuinely love to hear it as syntactically it looks extremely clean.