Stopping List.ForEach in C# 2.0

  • Thread starter Thread starter mike
  • Start date Start date
M

mike

Hello,

Are there any ways to stop List<T>.ForEach - method if e.g.
some condition is coming true?

Sample like

lst.ForEach(delegate(Item item)
{
...
if(item.Value == "Break")
<how to stop?>;
...
});

Cheers,

Michael
 
Are there any ways to stop List<T>.ForEach - method if e.g.
some condition is coming true?

Sample like

lst.ForEach(delegate(Item item)
{
...
if(item.Value == "Break")
<how to stop?>;
...
});

Doesn't look like it. ForEach() is an incredibly simple method that just
calls the Action<T> delegate for each item in the list. It has no logic for
breaking out of its loop.

If you need this conditional logic you'll have to write it yourself, and
really, it won't be hard.
 
mike said:
Are there any ways to stop List<T>.ForEach - method if e.g.
some condition is coming true?

Sample like

lst.ForEach(delegate(Item item)
{
...
if(item.Value == "Break")
<how to stop?>;
...
});
No, there's no way to prevent .ForEach() from visiting each item.

In general, don't use .ForEach() at all, it buys you exactly nothing
compared to a regular foreach statement.

foreach(Item item in lst) {
if (item.Value == "Break") break;
}

Shorter, clearer, works for anything enumerable, not merely lists -- and it
happens to be more efficient if "lst" is an array.

In a functional style (no side effects), you would search for the first item
that makes a particular condition true:

breakItem = list.FirstOrDefault(item => item.Value == "Break");
if (breakItem == null) {
// no break item in the entire list
}
 
Hello,

Are there any ways to stop List<T>.ForEach - method if e.g.
some condition is coming true?

Sample like

lst.ForEach(delegate(Item item)
{
     ...
     if(item.Value == "Break")
        <how to stop?>;
     ...

});

The only way to do it is to throw an exception and catch it outside.
Which is a really horrible solution, since the performance hit is
huge.

My recommendation is to not bother with List.ForEach and Array.ForEach
at all. They don't give you anything that a plain foreach loop
doesn't, they're less flexible in some aspects (as you've found out),
and they're not sufficiently generic (i.e. there's no
IEnumerable<T>.ForEach), so you can't use them in many common cases
anyway. It's easier to just forget they're there at all.
 
Paul said:
Don't forget 'continue;' if you want to skip over just that iteration.
"continue" is no more usable than "break" in a .ForEach() call. There is no
loop to break out of.

You can, of course, use "return" in this case to achieve the same effect.
 
Back
Top