Interview Questions and Answers for .NET - Language-Integrated Query (LINQ) (56)

Questions and answers taken from real job interviews.

Find real interview questions and answers on this website:

See right interview answers on 30 common job interview questions

Was this information helpful? Yes No

1. Advantage of LINQ over stored procedures

  Type Safety-linq has no default type .

Debugging- debugging of linq is quite easy rather than store procedure because it is part of .Net

While Store procedure written in sql database. Store Procedure offer few features to implement typical user task as compared to linq , Lambda expressions is one of best approaches to accomplish typical user required in optimal coding way.

2. Before you query a DataSet object by using LINQ to DataSet, you must first populate the dataset How can you do this?

You can load the data into the dataset by using different methods, such as:

• Using the DataAdapter class
• Using LINQ to SQL

3. Can I use LINQ with databases other than SQL Server? Explain how

LINQ supports Objects, XML, SQL, Datasets and entities. One can use LINQ with other databases through LINQ to Objects or LINQ to Datasets, where the objects and datasets then take care of database specific operations and LINQ only needs to deal with those objects, not the database operations directly.

4. Can you Concat two arrays to create one sequence that contains each array's values, one after the other?

Var ArrayA[]={4,8,7,9,4,7}

Var ArraB[] ={8,2,5,7,8,1}


Public Sub ConcatenateTwoArray()
Dim numbersA() = {4, 8, 7, 9, 4, 7}
Dim numbersB() = {8, 2, 5, 7, 8,1}

Dim allNumbers = numbersA.Concat(numbersB)

Console.WriteLine("All numbers from both arrays:")
For Each n In allNumbers
End Sub


5. Can you tell the advantages of LINQ over stored procedure?

  •  Debugging - LINQ supports .Net debugger, so we can easily debug a LINQ query using .NET debugger but it is not supported by SQL stored procedure so it is hard to debug the stored procedure. 
  •  Deployment - To deploy stored procedure it is necessary to write one more script to run them, while LINQ will complie by a single DLL statement and so the deployment will be simple. 
  •  Type Safety - As LINQ supports type safety so errors can be type checked in LINQ queries in compile time. 
  •  It is better to use LINQ as it enable us to identify the errors while compilation rather than runtime execution.

6. Difference between LINQ and Stored Procedures.

Difference between LINQ and Stored Procedures:

  • Stored procedures normally are faster as they have a 	predictable execution plan. Therefore, if a stored procedure is being executed 	for the second time, the database gets the cached execution plan to execute the 	stored procedure.
  • LINQ supports type safety against stored procedures.
  • LINQ supports abstraction which allows framework to add 	additional improvements like multi threading. It's much simpler and easier to 	add this support through LINQ instead of stored procedures.
  • LINQ allows for debugging using .NET debugger, which is not 	possible in case of stored procedures.
  • LINQ supports multiple databases against stored procedures 	which need to be re-written for different databases.
  • Deploying LINQ based solution is much simpler than a set of 	stored procedures

7. Differentiate between Conversion Operator ťIEnumerableŁ and ťToDictionaryŁ of linq.

IEnumerable and To Dictionary both are Conversion Operator which are used to solved to conversion type Problems.

''AsEnumerable '' operator simply returns the source sequence as an object of type IEnumerable<T>. This kind of ''conversion on the fly'' makes it possible to call the general-purpose extension methods over source, even if its type has specific implementations of them


public static IEnumerable<T> AsEnumerable<T>
this IEnumerable<T> source

''ToDictionary '' Conversion Operator is the instance of Dictionary (k,T) . The ''keySelector ''predicate identifies the key of each item while ''elementSelector '', if provided, is used to extract each single item.

Key and elementSelector Predicate can be Used in following ways-


Public void ToDictionatyExample()
Var scoreRecords=
new {Name = "Alice",Score = 50 },
new {Name = "Bob",Score = 40 },
new {Name = "Cathy", Score = 45} };
Var scoreRecordsDict = scoreRecords.ToDictionary(sr => sr.Name);
Console.WriteLine("Bob's score: {0}", scoreRecordsDict("Bob"));

Result: Bob's score: { Name = Bob, Score = 40 }

8. Disadvantages of LINQ over Stored Procedures

Disadvantages of LINQ over stored procedures:

  • LINQ needs to process the complete query, which might have 	a performance impact in case of complex queries against stored procedures which 	only need serialize sproc-name and argument data over the network.
  • LINQ is generic, whereas stored procedures etc can take 	full advantage of the complete database features.
  • If there has been a change, the assembly needs to be 	recompiled and redeployed whereas stored procedures are much simpler to update.
  • It's much easier to restrict access to tables in database 	using stored procedures and ACL's than through LINQ.

9. Give an example of Delete operation in LINQ to SQL.

  •  For Deletion of an item, remove the item from the collection to which it belongs, and then execute SubmitChanges on the DataContext to commit the deletion. 
  •  In the following example, the employee who has EmployeeID of 981 is retrieved from the database. Then, after ensuring that theEmployee data was retrieved, DeleteOnSubmit is executed to remove that object from the collection. 
  •  At last, SubmitChanges is executed to remove the row from the database.
  EmployeeDataContenxt db = new EmployeeDataContenxt();
  var deleteEmp =
  from emp in db.Employees
  where emp.EmployeeID == 981
  select emp;
  if (deleteEmp.Count() > 0)

10. Give an example of Insert operation in LINQ to SQL.

  •  For insertion of data in database we need to give values of each field to the entity class's object and then we have to use SubmitChanges method on the DataContext. 
  •  In the following example, a new Employee and his details are inserted to the Employee table by using InsertOnSubmit.

For example

// EmployeeDataContenxt inherits from System.Data.Linq.DataContext.
EmployeeDataContenxt db = new EmployeeDataContenxt();

Employee emp = new Employee();
emp.EmpName = "Arpit Jain";
emp.City = "Mumbai";
emp.EmployeeID = "123";
emp.Phone = "555-555-5555";
db.Employee.InsertOnSubmit(emp); // The new Employee object is added in the object model.
// In LINQ to SQL, the details will not be inserted in the database until
// SubmitChanges is executed.

11. Give example of get data from a table in LINQ to SQL.

  •  We can fetch the data from database table by simply writing a LINQ query and then running that query to retrieve the data. 
  •  LINQ to SQL will convert all the LINQ operation to the appropriate SQL operations that we are familiar with. 
  •  In the following example, the Names of employees from Mumbai are retrieved and shown in the console window.

// EmployeeDataContenxt inherits from System.Data.Linq.DataContext.
EmployeeDataContenxt db = new EmployeeDataContenxt();

var EmployeeNames =
from emp in db.Employee
where emp.City == "Mumbai"
select emp.EmpName;

foreach (var employee in EmployeeNames)

12. How can we find Sequence of Items in two different array (same Type) in the same order using linq query?

Public void MatchSequenceLinq()
Var wordsA = {"Rahul","ashok","sweta"};
Var wordsB = {"rahul","ashok","sweta"};
var match = wordsA.SequenceEqual(wordsB);
Console.WriteLine("The sequences match: {0}", match);

Output Result: True

13. How can you find average of student marks from student tables (Columns are StudentID, Marks)?


Public void LinqToSqlAverage()
var query = (from p in db. student. Marks).Average();


14. How can you open the O/R Designer?

You can open the O/R Designer by adding a new LINQ to SQL Classes item to a project.

15. How does LINQ to SQL differ from Entity framework?

  •  LINQ to SQL is suggested to use for fast development using SQL Server. Entity Framework is for enterprise level application and supports SQL server and other databases too. 
  •  LINQ to SQL classes maps one entity class with one database table. Entity Framework supports conceptual model which maps to storage model via mappings. 
  •  One Entity Framework class can be mapped to multiple tables or one table can be mapped to multiple classes. 
  •  LINQ is mainly targeted on rapid development whereas Entity Framework is for enterprise scenarios where the requirement is to create loosely coupled framework.

16. How to do a WHERE IN clause in LINQ to SQL?

-LINQ has "Contains" which is same as "IN" in SQL but the approach is different. An element isn't "in" a set, a set "contains" an element.

For example

int[] names = { ''Arpit'', ''Bob'', ''Jack'' };
var result = from emp in db.Employees
where names.Contains(emp.EmpId)
select emp

-It can also be written in simpler way with a lambda expression.
-int[] names = { ''Arpit'', ''Bob'', ''Jack'' };

var result = db.Employees.Where(emp => names.Contains(emp.EmpId));

17. How to Update data in LINQ to SQL? Give example.

  •  For Updation of data in database, first we need to get the item and update it in the object model. After we have changed the object, call SubmitChanges on the DataContext to update the database. 
  •  In the following example, Employee with EmployeeID 123 is retrieved. Then the name of the Employee is changed from "Arpit Jain" to "Arpit B. Jain". Finally,SubmitChanges is called to update the changes in the database. 
  •  For example
  EmployeeDataContenxt db = new EmployeeDataContenxt();
  var empData =
  from emp in db.Employees
  where emp.EmployeeID == 123
  select emp;
  empData.EmpName = "Arpit B. Jain";

18. In LINQ, lambda expressions underlie many of the standard query operators. Is it True or False?

It is true.

19. In which statement the LINQ query is executed?

A LINQ query is executed in the For Each statement in Visual Basic and in the foreach statement in C#.

20. List out the Data Context Functions. Where do we use ťSubmitChanges()Ł?

Create Database ()/Delete database ()

Database Exist ( )

Submit Changes ()

Create Query()


SubmitChanges()- SunbmitChanges Data Context Fuction Used to submit any update to the actual database.

21. Name the control that exposes the LINQ features to Web developers through the ASP.NET data-source control architecture.

The LinqDataSource control exposes the LINQ features to Web developers through the ASP.NET data-source control architecture.

22. On what parameter does the GroupBy clause group the data?

The GroupBy clause groups the elements that share a common attribute.

23. Partition following list of numbers by their remainder when divided by ť3Ł-{Var numbers() = {5, 4, 1, 3, 9, 8, 6, 7, 2, 0}}


Public Sub PartitioningExample()
Dim numbers() = {5, 4, 1, 3, 9, 8, 6, 7, 2, 0}

Dim numberGroups = From n In numbers Group n By key = n Mod 3 Into Group _
Select Remainder = key, NumberGroup = Group

For Each g In numberGroups
Console.WriteLine("Numbers with a remainder of {0} when divided by 3:", g.Remainder)
For Each n In g.NumberGroup
End Sub

24. Pros and cons of LINQ (Language-Integrated Query)

Pros of LINQ:

  • Supports type safety
  • Supports abstraction and hence allows developers to extend 	features such as multi threading.
  • Easier to deploy
  • Simpler and easier to learn
  • Allows for debugging through .NET debugger.
  • Support for multiple databases

Cons of LINQ:

  • LINQ needs to process the complete query, which might have 	a performance impact in case of complex queries
  • LINQ is generic, whereas stored procedures etc can take 	full advantage of database features.
  • If there has been a change, the assembly needs to be 	recompiled and redeployed.

25. The standard query operators are themselves a set of extension methods that provide the LINQ query functionality for any type that implements the IEnumerable<T> interface in Visual Basic. Is it True or False?

False, as it implements the IEnumerable(T) interface in Visual Basic and the IEnumerable<T> interface is implemented in C#.

26. What are lambda expressions in LINQ?

A lambda expression is a function without a name that calculates and returns a single value. All lambda expressions use the lambda operator =>, which read as goes to. The left side of the lambda operator specifies the input parameters and the right side holds the expression or statement block.

27. What are LINQ query expressions?

A LINQ query, also known as a query expression, consists of a combination of query clauses that identify the data sources for the query. It includes instructions for sorting, filtering, grouping, or joining to apply to the source data. The LINQ query expressions syntax is similar to the SQL syntax. It specifies what information should be retrieved from the data source.

28. What are standard query operators in LINQ?

The standard query operators in LINQ are the extension methods that form the LINQ pattern. These operators form an API that enables querying of any .NET array or collection. It operates on sequences and allows you to perform operations, such as determining if a value exists in the sequence and performing an aggregated function, such as a summation over a sequence.

29. What are the different implementations of LINQ?

The different implementations of LINQ are:

• LINQ to SQL - Refers to a component of.NET Framework version 3.5 that provides a run-time infrastructure to manage relational data as objects.
• LINQ to DataSet - Refers to a component that makes it easier and faster to query over data cached in a DataSet object.
• LINQ to XML - Provides an in-memory XML programming interface.
• LINQ to Objects - Refers to the use of LINQ queries with any IEnumerable or IEnumerable(T) collection directly, without the use of an intermediate LINQ provider or API, such as LINQ to SQL or LINQ to XML.

30. What are the different Visual Basic features that support LINQ?

Visual Basic includes the following features that support LINQ:

• Anonymous types - Enables you to create a new type based on a query result.
• Implicitly typed variables - Enables the compiler to infer and assign a type when you declare and initialize a variable.
• Extension method - Enables you to extend an existing type with your own methods without modifying the type itself.

31. What are the pros and cons of LINQ (Language-Integrated Query)?

Pros of LINQ:

  •  LINQ provides the type safety. 
  •  Abstraction is provided by LINQ and thus it enable us to use the concept of multithreading. 
  •  LINQ is easy to deploy as well as it is easy to understand. 
  •  Using .Net debugger we can debug the LINQ code. 
  •  LINQ allow us to use more than more one database together.

Cons of LINQ:

  •  In LINQ, it is necessary to process the whole query, and therefore it reduces the performance when we have large and complex queries. 
  •  It is generic, while we can use multiple feature of database using stored procedures. 
  •  In the case of any change in queries, we have to recompile and redeploy the assembly.

32. What is a LinqDataSource control?

The LinqDataSource control enables you to use LINQ. in an ASP.NET Web page by setting the properties in the markup text. You can use the control retrieve or modify data. It is similar to the SqIDataSource and ObjectDataSource controls in the sense that it can be used to declaratively bind other ASP.NET controls on a page to a data source. The difference is that instead of binding directly to a database or to a generic class, the LinqDataSource control is designed to bind a LINQ enabled data model.

33. What is benefit of using LINQ on Dataset?

  •  The major objective to use LINQ to Dataset is to execute strongly typed queries over Dataset. 
  •  Consider the scenario that you require to merge the results from two Datasets, or you require to take a distinct value from a Dataset, then we can use LINQ. 
  •  Usually we can use the SQL queries to execute on the database to get the Dataset, but we can't use SQL queries on a Dataset to retrieve a single value, for which use ofADO.NET features is necessary. 
  •  While, in case of LINQ, it supports better dignified way to execute queries on Dataset and gives some new functionalities than ADO.NET. 

34. What is Lambda Expressions? How can we optimize our linq code using this Expression?

Lambda expressions can be considered as a functional superset of anonymous
methods, providing the following additional functionality:

Lambda expressions can infer parameter types, allowing you to omit them.

Lambda expressions can use both statement blocks and expressions as bodies,
allowing for a terser syntax than anonymous methods, whose bodies can
only be statement blocks.

Lambda expressions can participate in type argument inference and
method overload resolution when passed in as arguments. Note: anonymous
methods can also participate in type argument inference (inferred return types).

In C#, a lambda expression is written as a parameter list, followed by the => token,followed by an expression or a statement block

35. What is Language Integrated Query (LINQ)?

LINQ is a programming model that is the composition of general-purpose standard query operators that allow you to work with data, regardless of the data source in any .NET based programming language. It is the name given to a set of technologies based on the integration of query capabilities into any .NET language.

36. What is Linq to SQL Deferred Loading?

(C#) -Deferred Loading is a property of Linq to sql, by default it is set true,

Exam - Let's have two tables -

Blogs Table (BlogID ,Blog Name,owner) and Post table ( PostID, BlogID, Title, Body)

To find Name and No's of posts in each blog-
BlogDataContext ctx = new BlogDataContext( );
var query = from b in ctx.Blogs select b;
foreach (Blog b in query)
Console.WriteLine("{0} has {1} posts", b.BlogName, b.Posts.Count);

Output of queries Produce Blog name with no's of post, But For each Blog 
Looping will be occurs (in case long list of blogs) that's reduces Overall Performance that's called the Deferred loading. 

37. What is Object Relational Designer (0/R Designer)?

The 0/R Designer provides a visual design surface to create LINQ to SQL entity classes and associations (relationships) that are based on objects in a database.

38. What is ťOfTypeŁ in linq?

public void TypeofExa()
Var numbers = {null,1.0,"two", 3,"four",5,"six",7.0 };

var doubles = from n in numbers where n is doublen;

Console.WriteLine("Numbers stored as doubles:");

foreach (object d in doubles) 


Numbers stored as doubles:

39. What is PLINQ?

PLINQ stands for Parallel Language Integrated Query. It is the parallel implementation of LINQ, in which a query can be executed by using multiple processors. PLINQ ensures the scalability of software on parallel processors in the execution environment. It is used where data grows rapidly, such as in telecom industry or where data is heterogeneous. 

PLINQ also supports all the operators of LINQ. In addition, you can query 'collections by using PLINQ. It can also run several LINQ queries simultaneously and makes use of the processors on the system. Apart from this, PLINQ uses parallel execution, which helps in running the queries quickly. Parallel execution provides a major performance improvement to PLINQ over certain types of legacy code, which takes too much time to execute.

40. What is Quantifiers in reference linq to Dataset?

Quantifier Operators return the Boolean value (either True or false) if some or all the elements in a sequence satisfy a condition,

Mainly two Quantifiers in linq -


Examples (vb)

''Any'' to determine if any of the words in the array contain the substring

Public Sub ExampleAny()

Dim words() = {"believe", "relief", "receipt", "field"}

Dim iAfterE = words.Any(Function(w) w.Contains("ei"))

Console.WriteLine("There is a word that contains in the list that contains 'ei': {0}", iAfterE)
End Sub


There is a word that contains in the list that contains 'ei': True

''All ''to return a grouped a list of products only for categories that have all of their products in stock

Public Sub Quantifier_All_Exam()

Dim products = GetProductList()

Dim productGroups = From p In products _
Group p By p.Category Into Group _
Where (Group.All(Function(p) p.UnitsInStock > 0)) _
Select Category, ProductGroup = Group

ObjectDumper.Write(productGroups, 1)
End Sub

41. What is the DataContext class and how is it related to LINQ?

After you add a LINQ to SQL Classes item to a project and open the O/R Designer, the empty design surface represents an empty DataContext class ready to be configured. The DataContext class is a LINQ to SQL class that acts as a conduit between a SQL Server database and the LINQ to SQL entity classes mapped to that database. This class contains the connection string information and the methods for connecting to a database and manipulating the data in the database. It is configured with connection information provided by the first item that is dragged onto the design surface.

42. What is the difference between the Select clause and SelectMany() method in LINQ?

Both the Select clause and SelectMany() method are used to produce a result value from a source of values. The difference lies in the result set. The Select clause is used to produce one result value for every source value. The result value is a collection that has the same number of elements from the query. In contrast, the SelectMany() method produces a single result that contains a concatenated collection from the query.

43. What is the difference between the Take and Skip clauses?

The Take clause returns a specified number of elements. For example, you can use the Take clause to return two values from an array of numbers. The Skip clause skips the specified number of elements in the query and returns the rest. For example, you can use the Skip clause to skip the first four strings in an array of strings and return the remaining array of string.

44. What is the function of the DISTINCT clause in a LINQ query?

The DISTINCT clause returns the result set without the duplicate values.

45. Which are the language extensions in C# 3.0 useful for LINQ?

  •  Lambda Expressions: If we want to create a delegate in LINQ then we can use a Lambda expression. 
  •  Anonymous Types: We can use Anonymous types to generate a bunch of read-only properties in a single object in which it is not necessary to define a type first. 
  •  Object Initializers: C# 3.0 supports Object Initializers to create and initialize the objects in s single step. 
  •  Implicitly Typed Variables: To achieve this we can use ''var'' keyword.

46. Which are the rules apply to a variable scope in lambda expressions?

  •  A variable used in lambda expression won't be garbage-collected until the delegate that references that variable is out of the scope. 
  •  Variables used in a lambda expression won't be accessible in the parent method. 
  •  A lambda expression can't get a ref or out parameter from an containing method. 
  •  The return statement used in a lambda expression won't return for the enclosing method. 
  •  A lambda expression does not support a goto, break or continue statement who point t outer the body.

47. Which command-line tool generates code and mapping for the LINQ to SQL component of .NET Framework?

The SqlMetal.exe command-line tool generates code and map the LINQ to SQL component.

48. Which extension method do you need to run a parallel query in PLINQ?

The AsParallel extension method is required to run a parallel query in PLINQ.

49. Which interface implements the standard query operators in LINQ?

The standard query operators implement the IEnumerable<T> or the IQueryable<T> interface in C# and the IEnumerable(Of T) or the IQueryable(Of T) interface in Visual Basic.

50. Why do we use ťContainsŁ method for strings type functions?

Contains method Used to find all matching records From Given string using 
Matching keywords,


This Examples returns the Customer Names from Customer tables whose Names have contains ''Anders''

Public void LinqToSqlStringUsingContains()
Var q = From c In db.Customers _
Where c.ContactName.Contains("Anders") _
Select c

51. Why var keyword is used and when it is the only way to get query result?

  •  var is a keyword introduced in C# 3.0. It is used to substitute the type of the variable with a generalized keyword. 
  •  The compiler infers the actual type from the static type of the expression used to initialise the variable. 
  •  It is must to use the var keyword when we deal with the queries which returns anonymous type. E.g. 
  var results = from t in MyStringData
  select new
  NoOfLetter = t.Length,
  CapitalString = t.ToUpper()
  foreach (var result in results)
  Console.WriteLine(result.NoOfLetter + " " + result.CapitalString);

52. Write a Program for Concat to create one sequence of Data Rows that contains DataTables's Data Rows, one after the other.


Public void Datasetlinq()
var numbersA = TestDS.Tables("NumbersA").AsEnumerable();
var numbersB = TestDS.Tables("NumbersB").AsEnumerable();
var allNumbers = numbersA.Concat(numbersB);
Console.WriteLine("All numbers from both arrays:");
foreach (object n_loopVariable in allNumbers) {
n = n_loopVariable;

53. Write a Program using Skip and Take operators. How can it beneficial for bulky data accessing on page?

''skip'' and ''take'' Operator used for Paging. Suppose we have Customer table of 100 records. To find 10 records by skipping the first 50 records from customer table-

Public void Pagingdatasource ()
Var Query =from CusDetails in db.customer skip (50) Take (10)

Hence The LinQ '' SKIP'' operator lets you skip the results you want, and ''Take'' Operator enables you yo select the rest of result . So By Using Skip and Take Operator, You can create paging of Specific sequence.

54. Write small Program to generate Xml Document from table like (StudentRecord Table) using linq query

Public void CreateXmlDocFromArray()


// Now enumerate over the array to build an XElement.
XElement StudentRecords =
new XElement("StudentInfo",
from c in Student 
select new XElement("Student",
new XAttribute("Name", c.Name),
new XElement("RollNo", c.RollNo)

55. Write the basic steps to execute a LINQ query.

The following are the three basic steps to execute a LINQ query:

• Obtain the data source (The data source can be either an SQL database or an XML file)
• Create a query
• Execute the query

56. Write the basic syntax of a LINQ query in Visual Basic as well as in C#.

In Visual Basic, the basic syntax of a LINQ query starts with the From clause and ends with the Select or Group By clause. In addition, you can use the Where, Order By, and Order By Descending clauses to perform additional functions, such as filtering data and generating the data in a specific order.

In C#, the basic syntax of a LINQ query starts with the From clause and ends with the Select or group by clause. In addition, you can use the where, orderby, and Orderby descending clauses to perform additional functions, such as filtering data and generating the data in a specific order.

Do you know that?

biggest challenge for 41.8% freelancers is to find clients Next



Fast Payments
Payoneer sing up to get free