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
- The string array is initialized with 4 items (new, old, big, small)
- The list of phones is sorted by length of items within the list (using .OrderBy(...)),
- then filtered to only such items that have their length equal to 5 (using .Where(...))
- and in the end single item is returned (using .Single(...)) and written to the console.
- 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
-
What is boxing and unboxing?
.NET C# Performance Junior -
Do you use generics? What are they good for? And what are constraints and why to use them?
.NET C# Performance Mid-level -
Could you explain on the following example what a deferred execution is and what materialization is? What will the output be?
.NET C# LINQ Performance Mid-level -
What array initialization syntaxes do you know?
.NET C# Mid-level -
How does the .Max(...) work in LINQ? What will be the result of the following code?
.NET C# LINQ Junior