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: .NETC#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?
.NETC#Performance JuniorDo you use generics? What are they good for? And what are constraints and why to use them?
.NETC#Performance MediorCould you explain on the following example what a deferred execution is and what materialization is? What will the output be?
.NETC#LINQPerformance MediorWhat array initialization syntaxes do you know?
.NETC# MediorHow does the .Max(...) work in LINQ? What will be the result of the following code?
.NETC#LINQ Junior