Question

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 ?
        });
Was it helpful?

Solution

You cannot achieve this with ForEach.

OTHER TIPS

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;

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.

While not recommended you can throw an exception from inside the ForEach() when the condition is satisfied.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top