Time for action – picking conditionally

Here is the first problem:

Say we have a List of names and we want to create another List picking names from this List as long as the names start with "S". Here is how we can do that using TakeWhile():

  1. Copy the following code snippet as a query to LINQPad:
    string[] names  = { "Sam", "Samuel", "Dave", "Pascal", "Erik", "Sid" };
    var sNames = names.TakeWhile(c => c.StartsWith("S"));
    sNames.Dump("S* Names");
  2. Run the query. You should get the following output:
    Time for action – picking conditionally

What just happened?

If you are thinking, why "Sid" didn't make it to the List of the matching names, you are not alone. I thought so too initially. However, you ...

Get .NET 4.0 Generics now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.