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()
:
- 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");
- Run the query. You should get the following output:
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 books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.