Could you explain what the following LINQ methods OrderBy, Where and Single do and what will be the output of the code?

var phones = new []{ "new", "old", "big", "small" };

Console.WriteLine(phones.OrderBy(p => p.Length).Where(p => p.Length == 5).Single());

Experience Level: Junior
Tags: .NET C# LINQ

Answer

Answer

  1. The string array is initialized with 4 items (new, old, big, small)
  2. The list of phones is sorted by length of items within the list (using .OrderBy(...)),
  3. then filtered to only such items that have their length equal to 5 (using .Where(...))
  4. and in the end single item is returned (using .Single(...)) and written to the console.
  5. What's important is that Single() verifies that only one matching result exists in IEnumerable. If that is the case, the matching item is returned. If zero or more items are within the IEnumerable, exception is thrown.
Related C# job interview questions