Time for action – checking whether there is only one item matching this pattern

Follow the given steps:

  1. Copy the following as a query to LINQPad:
    string[] names = { "Sam", "Danny", "Jeff", "Erik", "Anders" };
    string onlyOne = names.Single(c => c.StartsWith("Dan"));
    onlyOne.Dump("Only name with Dan*");
  2. Run the query and you should get the following output:
    Time for action – checking whether there is only one item matching this pattern

What just happened?

This will have "Danny" stored in onlyOne as that's the only name in the sequence names that starts with "Dan". However, the following snippet will throw an exception as there is more than one element in the source collection:

try { string w = names.Single();//This line will throw ...

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.