Linq Interview Questions by Example, how and why!

The following question was set for me recently. I had the advantage that my recruiter gave me a heads up on what to expect and I could play around with writing the clearest solution while not under the intense pressure of an interview.

I’m in two minds about pre-warning candidates what they should expect in an interview, on the one hand you’re undermining the interview process and potentially giving certain candidates an advantage. On the other hand (and this definitely applies to me), you’re not going to get the best out of a candidate that’s stressing due to being in an interview. Giving a heads up lets people prepare and ultimately remain calm and give a better performance.

Ultimately, I think that if you’re marking people strictly on their solution, you’re probably doing it wrong. You should use the coding question as a jumping off point for discussion and it’s the answers they give during the Q&A that should be the deciding factor.

I’m putting this here to give anyone interested enough, the chance to prepare.

Contents

The Linq Interview Question

“Given a string of words, write some code to reverse them.”

My Solution

using System;
using System.Linq;

public class Program
{
  public static void Main()
  {
    var myString = "The quick brown fox jumps over the lazy dog";
    Console.WriteLine(Reverse(myString));
  }

  public static string Reverse(string input)
  {
    return String.Join(" ", input.Split(' ').Reverse());
  }
}

All the work is done in this line, the rest is just scaffolding:

return String.Join(" ", input.Split(' ').Reverse());

Discussion

Breaking this down:

First, the string is split into an array of words using input.Split(‘ ‘). The official String.Split() documentation might help with understanding this.

Then, the Linq happens! we’re only using one method, but it’s a great one for this use case: .Reverse(). I’ve written about this method before in my post on Linq Except and it’s brethren.

Finally, the array is reconstituted back into a large string with String.Join() before being retrurned.

All in all, there’s not much to this solution, but especially in interviews, they’re often looking for the simple elegant solution.

Conclusion

If you want to read about some of the other Linq extention methods that you might get tested on, you could do worse that checking out my post on Except and other set based Linq methods: C# Linq Except: How to Get Items Not In Another List.

To put your mind at ease, yes I did pass this particular interview! Though the rounds after this did get trickier. I’ll save all the juicy bits for a future post.

2 Replies to “Linq Interview Questions by Example, how and why!”

Leave a Reply

Your email address will not be published. Required fields are marked *