Please navigate to the bottom of the page for Table of Contents

Saturday, July 28, 2012

LINQ interview questions part 2

Based on popular demand, I am posting a follow up post to my first LINQ interview questions article. In this post, we will follow a similar pattern of rapid fire interview questions and answers on LINQ concepts.

Question 1: How can you sort a result set based on 2 columns?

Assume that you have 2 tables – Product and Category and you want to sort first by category and then by product name.

var sortedProds = _db.Products.Orderby(c => c.Category).ThenBy(n => n.Name) 


Question 2: How can you use LINQ to query against a DataTable?


You cannot query against the DataTable's Rows collection, since DataRowCollection doesn't implement IEnumerable<T>. You need to use the AsEnumerable() extension for DataTable. As an example:

var results = from myRow in myDataTable.AsEnumerable() 
where myRow.Field<int>("RowNo") == 1
select myRow;


Question 3: LINQ equivalent of foreach for IEnumerable<T>


There is no ForEach extension for IEnumerable; only for List. There is a very good reason for this as explained by Eric Lippert here.

Having said that, there are two ways you can solve this:

Convert the items to list and then do a foreach on it:


items.ToList().ForEach(i => i.DoStuff());



Or, alternatively, you can write an extension method of your own.


public static void ForEach<T>(this IEnumerable<T> enumeration, Action<T> action) 
{
foreach(T item in enumeration)
{
action(item);
}
}



Question 4: When to use .First and when to use .FirstOrDefault with LINQ?


You should use First when you know or expect the sequence to have at least one element. In other words, when it is an exceptional if the sequence is empty.

Use FirstOrDefault, when you know that you will need to check whether there was an element or not. In other words, when it is legal for the sequence to be empty. You should not rely on exception handling for the check.

Question 5: Write a LINQ expression to concatenate a List<string> in a single string separated by a delimiter.

First of all, it is better to use string.Join to tackle this problem. But for interview purposes, this problem can be approached as follows:


string delimeter = ","; 
List<string> items = new List<string>() { "foo", "boo", "john", "doe" }; 
Console.WriteLine(items.Aggregate((i, j) => i + delimeter + j)); 

Question 6: Write a LINQ expression to concatenate a List<MyClass> objects in a single string separated by a delimiter. The class provides a specific property (say Name) that contains the string in question.



items.Select(i => i.Name).Aggregate((i, j) => i + delimeter + j)

8 comments: