Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# exit generic ForEach that use lambda

Does anyone know if it is possible to exit a generic ForEach that uses lambda? e.g.

someList.ForEach(sl =>
  {
    if (sl.ToString() == "foo")
        break;

    // continue processing sl here
    // some processing code
  }
);

This code itself won't compile. I know I could use a regular foreach but for consistency I want to use lambda.

Many thanks.

like image 388
Peanut Avatar asked Feb 12 '10 03:02

Peanut


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr. Stroustroupe.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is C language basics?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.


1 Answers

Sure. But first, note that I recommend against this; I say that a sequence operator should not have a side effect, and a statement should have a side effect. If you're doing something in that ForEach lambda, then make it a statement in the body of a foreach loop rather than making it look like a sequence operator.

That said, here's what you do. First, you write yourself a ForEach that works on arbitrary sequences, not just lists:

public static void ForEach<T>(this IEnumerable<T> sequence, Action<T> action)
{
    foreach(var item in sequence) action(item);
}

And now you write your break like this:

someList
    .TakeWhile(x=>x.ToString() != "foo")
    .ForEach(sl=>
    {/*your action here*/});
like image 68
Eric Lippert Avatar answered Nov 15 '22 21:11

Eric Lippert