views:

507

answers:

4

How do i exit a Generic list ForEach with a delegate? Break or return doesn't work.

Example:

        Peoples.ForEach(delegate(People someone)
        {
            if(someone.Name == "foo")
               ???? What to do to exit immediatly ?
        });
+1  A: 

You cannot achieve this with ForEach.

Darin Dimitrov
+1  A: 

just write it out like this

foreach(People someone in Peoples)
{
    if(someone.Name == "foo") break;
    // rest of code below for != "foo"...
}

to just skip foo and still do the action for everyone else you could do

if(someone.Name == "foo") continue;
Mark Dickinson
A: 

You could do something like:

        Peoples.TakeWhile(p=> p.Name != "foo")
            .ToList().ForEach(p => Console.WriteLine(p.Name));

but that's overkill and bad in terms of performance ...

Just use a simple foreach loop.

bruno conde
A: 

You can achieve this, but not recommended.

Hint: use exceptions :)

leppie
Costly though. Exceptions are not part of normal behaviour of a program, the clue is in the name. :)
Mark Dickinson