Top 20 LINQ Interview questions and answers

Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
LinkedIn

Never miss a post!

Sign up for our newsletter and get FREE Development Trends delivered directly to your inbox.

You can unsubscribe any time. Terms & Conditions.
Categories

We grouped together a list of the top LINQ interview questions. If you are looking for a .NET developer role, LINQ is highly used to interact with databases and lists. We highly recommend you go through these questions and answers and test your knowledge. These LINQ interview questions can serve as a revision or prepare you for your next interview.

1. What is LINQ?

LINQ also known as Language Integrated Query is a way of querying data in .NET using a similar approach to SQL query. It is capable of querying any type of data. LINQ can be used as an abstraction layer from the actual SQL query language. LINQ is supported in C# and VB.NET.

2. What are the different types of LINQ?

The types of LINQ types are the following, LINQ to:

  • Objects
  • XML
  • Dataset
  • SQL

3. Explain what Standard Query Operators are

Standard query operators are LINQ queries that are performed on sequences. A sequence is a collection class object which implements the IEnumerable<T> interface or the IQueryable<T> interface. The Standard Query operators perform query functionalities such as filtering, projection, aggregation, sorting and others.

There are two types of LINQ standard query operators:

  • LINQ operators that work with objects of type IEnumerable<T>
  • LINQ operators that work with of type IQueryable<T>

4. Specify the use of Extension Methods and give some examples

Extension methods are static methods in a static class. They can be invoked in a similar way when instantiating. These methods are used when the class will not be manipulated.

The following are some examples of extension methods:

Projection Operator – Select and SelectMany

  • “Select” operator – Used to select values from a data source like collections
  • “SelectMany” operator – Used to select values from collections of a collection
// Select the ids in from a collection storing employee objects
List<int> ids = (from employee in GetEmployees() select emp.ID).ToList();

// Combine the collection of strings into a collection of characters
List<string> names =new List<string>(){"Kurt", "Cobain" }; 
IEnumerable<char> methodSyntax = nameList.SelectMany(x => x);

Filtering operator – Where and OfType<>

They are used to filter collections based on particular conditions.

  • “Where” operator – works the same as the Where SQL operator
  • “OfTtype” operator – filters collections based on specified types.
List<int> numbers = new List<int> { 11, 12, 13, 14, 15, 16, 17, 18, 19, 11 };
// List all the numbers greater than 15
IEnumerable<int> filteredList = numbers.Where(num => num > 15);
List<object> objectList = new List<object>()
{
         "Jame", "Loves", 6, "Loves", "His", 20, "toys"
};

// Return a list of integers
List<int> intlist = objectList.OfType<int>().ToList();
Grouping operator – GroupBy and LookUp
  • GroupBy operator – yields a group of elements based on a group key value. For example, listing students in the same course where the course is the group.
  • ToLookUp operator – performs the exact same thing but GroupBy operator performs deferred execution whereas ToLookup performs immediate execution
// Group employees by name
var EmployeesByName = employees.GroupBy(s => s.Name);

// Group employees by name using ToLookup
var EmployeesByName = employees.ToLookup(s => s.Name);

Sorting operator – OrderBy

  • “OrderByDescending” operator – Ordered by descending order
  • “OrderBy” operator – Sorted by ascending order

Reverse operatorReverse

  • Reverses the order of the list.

5. What are Anonymous data types?

Anonymous data types are dynamically generated by the compiler in runtime. Property names are created and a value is assigned to them at runtime. This means you do not need to give it a name when creating an anonymous data type.

Anonymous types cannot implement interfaces, specify methods or define static methods.

In LINQ, Anonymous types can be used in the SELECT clause. When using SELECT, an anonymous type is generated so that the query can include properties undefined in the class.

6. What are Anonymous Functions and how can they be used in LINQ?

There are two types of Anonymous functions in C#

  • Anonymous methods – Instead of using the named method as shown in code snippet (see comments), we can use the delegate keyword for unnamed anonymous methods (see below). Anonymous methods include the code inside curly brackets. Note: In the example below, it is only one line of code. But the code inside the curly brackets can be several lines long.

  • Lambda expressions – Introduced in C# 3.0, Anonymous functions allow a more simple way of writing anonymous functions. It is essentially a shortcut to writing delegates. Lamba expressions are used to write inline functions and are passed as arguments to a function or returned as arguments from a function. To understand better the syntax (see code snippet below), you specify the input parameters on the left, the Lamda operator at the centre and the expression or in-line code on the right-hand side of the operator.

public static void Main(string[] args) 
{ 
   var users = new List<User> { new User{Name="Bran",Surname="Stark", UserId=1001},
                                new User{Name="John",Surname="Snow", UserId=1002}, 
                                new User{Name="Arya",Surname="Stark", UserId=1003}, 
                                new User{Name="Theon",Surname="GreyJoy", UserId=1004}, };

 //Lambda Expression 
users.Where(x => x.Surname == "Stark"); 
//Anonymous Method C#2.0 
users.Where(delegate (User user) { return user.Surname == "Stark"; });
//Named Method 
users.Where(IsPartOfStarkFamily); 
} 
//Named Method 
public static bool IsPartOfStarkFamily(User user) 
{
  return user.Surname == "Stark"; 
}

7. What is an Action delegate in LINQ?

Action delegate in C# represents a delegate that has no return type (void) and optional parameters. The number of parameters it can support is up to 16 of different data types. Here is an example of a declaration of an Action delegate:

Action<double,double> bmi = CalculateBMI;

So if we had to call this action we would do the following:

static List<User> users = new List<User>(); 
static void CalculateBMI(double mass, double height) 
{ 
   Console.WriteLine($"Your BMI is {mass / Math.Pow(height / 100.0, 2)}");
} 

static void Main(string[] args) 
{ 
   Action<double, double> bmi = CalculateBMI; users.ForEach(x => bmi(x.Mass, x.Height)); 
}

8. What is a Func delegate in LINQ?

A Func delegate is a special type of delegate called Multicast Delegate that is used to return values in methods. It is highly used in LINQ and Enumerable extension methods. It has the following properties:

  • It can contain up to 16 input parameters of different or same types
  • It must contain ONE output parameter
  • It cannot contain ref or out parameters.
public static bool EnumerableContains<S, T>(this IEnumerable<S> obj, Func<S, T> comparer, T valueToMatch)
{ 
   return obj.Any(l => comparer(l).Equals(valueToMatch)); 
}

9. What are the differences between LINQ and Stored Procedures?

Advantages of using LINQ

The advantage of using LINQ is that it easier to debug LINQ queries with Visual Studio’s Debugger in comparison to debugging Stored Procedures. Reason being, Stored Procedures require you to add a script for deployment in order for you to use them. In contrast, with LINQ the deployment is simple as the code is compiled as one DLL. Additionally, LINQ is Type-safe meaning any errors are checked for at compile time. Also, LINQ supports various .NET Framework features such as multithreading, unlike stored procedures.

Disadvantages of using LINQ 

However, you need to note that Stored procedures are faster than LINQ since they have a predictable execution plan and can take advantage of SQL features. Since its predictable, this means the database caches the stored procedure before the next execution. Stored Procedures are also preferable if your query is quite complex. Moreover, if you want to apply a bulk insert or update operations, Stored procedures perform much better.

10. What is the benefit of using LINQ Dataset?

The benefit of using LINQ Dataset is to run strongly typed queries using LINQ. LINQ is used to combine two datasets or to extract a particular value from a data set.

You can use SQL queries to populate a data set, but you cannot use SQL queries to retrieve values. If you needed to retrieve values, you would have to use ADO.NET Functionalities. However, when using LINQ, it is much clearer to query the dataset. Moreover, LINQ provides more features when compared to ADO.NET.

11. What are LINQ query expressions?

A LINQ query expression is a query written in query syntax. It is a first-class language construct. A query expression consists of a set of clauses written in a declarative syntax similar to SQL. The query expression must start with a FROM clause and end with a SELECT or GROUP clause. It can also contain one or more of these optional clauses: WHERE, ORDER BY, JOIN, LET and another additional FROM clause. You can also use INTO to be able to retrieve the result of a JOIN into a secondary query.

12. What is PLINQ?

PLINQ stands for Parallel Language Integrated Query. With PLINQ, a query can be executed in parallel using multi-processors. The queries can be scaled to work across multiple environments during execution. It supports all types of operators in LINQ and runs them asynchronously.

13. Define what is Where clause and Let clause?

The WHERE clause gives you the possibility to add a conditional filter to your query.

The LET clause lets you define a variable and assign it a value that is calculated from the data values.

14. What is the difference between the Take and Skip clause?

The TAKE clause is used to return only a specified number of elements from the list.

users.Take(5); //Will only take the first 5 elements from the users list
users.Skip(5); //Will skip the first 5 elements from the users list

The TAKE clause will skip a specified number of elements and returns the rest only. You can also use TakeLast to take the last N elements of the list or TakeWhile() to retrieve elements depending on a certain condition.

The SKIP clause is used to return only a specified number of elements. The Skip clause, on the other hand, skips a specified number of elements and returns the rest only. Just like Take, you can also choose to use SkipLast() to skip the last number of elements and SkipWhile() to bypass a number of elements depending on the condition given.

15. Explain why SELECT clause comes after FROM clause in LINQ?

LINQ requires that all the variables need to be declared first. FROM clause of LINQ query defines the range of conditions to select records. Therefore FROM clause needs to appear before SELECT in LINQ.

16. Explain what is the difference between Skip() and SkipWhile() extension method?

Skip() – It will skip the top N numbers from an object of type IEnumerable where N is passed as an argument.

SkipWhile() – Given an input condition, it will continue to skip the elements while the condition remains true. It will then return all the remaining elements if the condition is false.

17. Explain how you can retrieve a single row with LINQ?

You can retrieve a single row using Single() or SingleOrDefault(). You can also choose to retrieve the first row by using First() or FirstOrDefault()

public User GetUser(string surname)
{
  DBNameDataContext myDB = new DBNameDataContext();
  User user = myDB.Users.SingleOrDefault(u, u.surname => userName);
  return user;
}

18. How can you retrieve the index of the element using WHERE clause with Lambda Expressions?

To be able to find the index of the element using the WHERE clause you must apply the following lambda expression:

Where ( ( i, ix ) => i == ix);

19. Can you explain what compiled queries are?

Compiled LINQ Queries are a cached version of the actual query. The first time we execute the query, it is parsed or verified for syntax errors in LINQ. Next, it is converted into an SQL version and added into the cache. The next time you run the query, it will be run from the cache.

20. Differentiate between the conversion operator ToDictionary and IEnumerable of LINQ.

To resolve conversion type issues, AsEnumerable and ToDictionary conversion operators are used.

ToDictionary – This conversion operator is an instance of the Dictionary(k,T). The key selector (k) predicate retrieves the key of each item while elementSelector (T) is used to retrieve the value for each item.

AsEnumerable is used to return the source sequence as an object of type IEnumerable.

Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
LinkedIn

Our website uses cookies that help it to function, allow us to analyze how you interact with it, and help us to improve its performance. By using our website you agree by our Terms and Conditions and Privacy Policy.