Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Linq PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

LINQ Interview Questions and Answers

All rights reserved. No part of this book can be reproduced or stored in any retrieval system, or transmitted in any
form or by any means, electronic, mechanical, photocopying, recording, uploading on server and scanning without
the prior written permission of the author.

The author of this book has tried his best to ensure the accuracy of the information described in this book.
However, the author cannot guarantee the accuracy of the information contained in this book. The author will
not be liable for any damages, incidental or consequential caused directly or indirectly by this book. Further,
readers should be aware that the websites or reference links listed in this book may have changed or disappeared
between when this book was written and when it is read.

All other trademarks referred to in this book are the property of their respective owners.

Release History
 Initial Release 1.0.0 - 1st Jul 2014
 Second Release 1.0.1 - 1st Jan 2015
 Third Release 1.0.2 - 12th Aug 2016

1
Page
Dedication

My mother Mrs. Vriksha Devi and my wife Reshu Chauhan deserve to have theirs name on the cover as
much as I do for all theirs support made this possible. I would like to say thanks to all my family members
Virendra Singh(father), Jaishree and Jyoti(sisters), Saksham and Pranay(sons), friends, to you and to
readers or followers of my blog www.dotnettricks.com to encourage me to write this book.
I would like to give a special thanks to Kanishk Puri and Avadhesh Sengar for actively participating in the
feedback and contributions for this book via theirs valuable feedback and suggestions.

-Shailendra Chauhan

2
Page
Introduction

Writing a book has never been an easy task. It takes a great effort, patience and consistency with strong
determination to complete it. Also, one should have a depth knowledge over the subject is going to write.

So, what where my qualification to write this book? My qualification and inspiration come from my enthusiasm
for and the experience with the technology and from my analytic and initiative nature. Being a trainer, analyst,
consultant and blogger, I have through knowledge and understandings of .NET technologies. My inspiration and
knowledge has also come from many years of my working experience and research over it.

So, the next question is who this book is for? This book is appropriate for novice as well as for senior level
professionals who want to understand what LINQ does, how it does in .NET languages like C# and VB. This book is
equally helpful to show you the best of using LINQ with the help of many practical ways to make your daily
programming life easier and more productive.

This book is not only help you to learn LINQ but it also be helpful to learn Entity Framework. This book helps you
to do hands on LINQ as well as preparing yourself for an interview on LINQ.

I hope you will enjoy this book and find it useful. At the same time, I also encourage you to become a continue
reader of my blogs www.gurukulsight.com, www.dotnettricks.com and be the part of the discussion. But most
importantly practice a lot and enjoy the technology. That’s what it’s all about.

To get the latest information on LINQ, I encourage you to follow the MSDN at http://msdn.microsoft.com/en-
us/library/bb397926.aspx. I also encourage you to subscribe to my blogs at www.gurukulsight.com,
www.dotnettricks.com that contains .NET, C#, ASP.NET MVC, LINQ, Entity Framework, jQuery and many more
tips, tricks and tutorials.

As the author, I am absolutely delighted about this. It's been a work of love and I want it to reach as many techy
people as possible.

All the best for your interview and happy programming!

3
Page
About the Author

Shailendra Chauhan - An Entrepreneur, Author, Architect,


Corporate Trainer, and Microsoft MVP
With more than 7 years in hand experience, Shailendra Chauhan is a
polymath in the domains of Microsoft .NET technologies and an array of
other technologies including JavaScript, AngularJS, Node.js, Ionic and
NoSQL Databases to name but a few.

His extensive knowledge has been broadcast in a number of articles-of-the-


day, and reported in daily-community-spotlight along with being listed in
Recommended Resources for MVC section on the Official Microsoft ASP.NET
Community Site. He has rewarded as Microsoft MVP for his exceptional
contributions in Microsoft Visual Studio and Development Technologies.

Shailendra is the author of some of most popular e-books which encompass technical Interview on AngularJS
Interview Questions and Answers, LINQ Interview Questions and Answers and MVC Interview Questions and
Answers. Furthermore, he is a technical reviewer for book on ASP.NET MVC 4 Mobile App Development.

Shailendra Chauhan is renowned for sharing his working experience, research and knowledge through his reputed
and widely subscribed to blogs - www.gurukulsight.com and www.dotnettricks.com. Specifically, his blog
www.dotnettricks.com provides a vast storehouse of knowledge and support resources in the field of .NET
technologies worldwide and is listed as a non-Microsoft resource in The Microsoft Official Community Site. His
blogs and training approach provide an easily accessible and highly innovative learning experience for people
everywhere, and from a range of backgrounds and skill levels thereby offering the ultimate in training around the
world.

Moreover, and to his credit he has delivered 200+ training sessions to professionals world-wide in Microsoft .NET
technologies and other technologies including JavaScript, AngularJS, Node.js, Ionic and NoSQL Databases. In
addition, he provides Instructor-led online and classroom training programs for all above technologies.

Shailendra’s strong combination of technical skills and solution development for complex application
architecture with proven leadership and motivational skills have elevated him to a world renowned status,
placing him at the top of the list of most sought after trainers.

“I always keep up with new technologies and learning new skills to deliver the best to my students” says
Shailendra Chauhan, he goes on to acknowledge that the betterment of his followers and enabling his students to
realize their goals are his prime objective and a great source of motivation and satisfaction.

Shailendra Chauhan - “Follow me and you too will have the key that opens the door to success”
4
Page
How to Contact Us

Although the author of this book has tried to make this book as accurate as it possible but if there is something
strikes you as odd, or you find an error in the book please drop a line via e-mail.

The author e-mail addresses are listed as follows:

 shailendra@dotnettricks.com
 info@dotnettricks.com

I am always happy to hear from my readers. Please provide with your valuable feedback and comments!

You can also follow us on facebook, twitter, linkedin, google plus or subscribe to RSS feed.

5
Page
Table of Contents

LINQ Interview Questions and Answers .......................................................... 1


Dedication ....................................................................................................... 2
Introduction .................................................................................................... 3
About the Author ............................................................................................ 4
How to Contact Us .......................................................................................... 5
LINQ ................................................................................................................ 9
Q1. What is LINQ and why to use it? ................................................................................................................9
Q2. Which namespace is necessary to use LINQ?.............................................................................................9
Q3. What are different flavors of LINQ? ...........................................................................................................9
Q4. What are advantages of LINQ? ................................................................................................................ 10
Q5. What are disadvantages of LINQ? ........................................................................................................... 10
Q6. What are different methods to write LINQ Query? ................................................................................ 10
Q7. How var type is different from anonymous type? .................................................................................. 12
Q8. What is anonymous method? ................................................................................................................. 13
Q9. What is lambda expression?.................................................................................................................... 14
Q10. What is Extension method?..................................................................................................................... 15
Q11. What is LINQPad? .................................................................................................................................... 17
Q12. What LINQ providers are supported by LINQPad? .................................................................................. 17
Q13. What is LINQ Insight? .............................................................................................................................. 17
Q14. What are Quantifiers? ............................................................................................................................. 17
Q15. What are different types of operators in LINQ?...................................................................................... 17
Q16. What are aggregate operators? .............................................................................................................. 18
Q17. What are conversion operators? ............................................................................................................. 18
Q18. What are element operators? ................................................................................................................. 18
Q19. What is difference among Single, SingleOrDefault, First and FirstOrDefault?........................................ 19
Q20. When to use Single, SingleOrDefault, First and FirstOrDefault? ............................................................. 19
6

Q21. Which one is fast between SingleOrDefault and FirstOrDefault? ........................................................... 20


Page
Q22. What is LINQ provider and what are different types of LINQ providers? ............................................... 20
Q23. What are advantages of using LINQ on DataSet? ................................................................................... 20
Q24. What is difference between Select and SelectMany in LINQ? ................................................................ 20
Q25. What is difference among Any, All and Contains? .................................................................................. 22
Q26. What is difference between into and let keyword in LINQ? ................................................................... 22
Q27. Explain Union, Intersect and Except? ...................................................................................................... 23
Q28. What is the extension of the file, when LINQ to SQL is used? ................................................................ 23
Q29. What is data context class? Explain its role? ........................................................................................... 23
Q30. What are deferred execution and immediate execution? ...................................................................... 23
Q31. What are lazy/deferred loading and eager loading? ............................................................................... 24
Q32. Can you disable lazy/deferred loading? .................................................................................................. 27
Q33. What is explicit loading?.......................................................................................................................... 27
Q34. What are different types of joins in LINQ? .............................................................................................. 27
Q35. How to write LINQ query for Inner Join with and condition? ................................................................. 29
Q36. How to write LINQ query for Inner Join with OR condition? .................................................................. 29
Q37. Write LINQ query to find 2nd highest salary? ......................................................................................... 30
Q38. How to use GroupBy in LINQ? ................................................................................................................. 30
Q39. How to use Having in LINQ? .................................................................................................................... 30
Q40. What is Expression?................................................................................................................................. 31
Q41. What is Expression Trees? ....................................................................................................................... 31
Q42. How can you create Expression Trees? ................................................................................................... 31
Q43. How Expressions Trees are different from Lambda Expression? ............................................................ 32
Q44. How LINQ query is compiled to Expression Trees? ................................................................................. 32
Q45. What is difference between IEnumerable and IQueryable? ................................................................... 33
Q46. When to use var or IEnumerable to store query result in LINQ? ............................................................ 34
Q47. What is difference between IEnumerable and IList? .............................................................................. 34
Q48. What is SQL metal in LINQ? ..................................................................................................................... 35
Q49. What is difference between LINQ and Stored Procedures? ................................................................... 35
Q50. What are disadvantages of LINQ over Stored Procedures? .................................................................... 35
Q51. What is difference between XElement and XDocument? ....................................................................... 36
7

Q52. What is difference between XElement.Load() and XDocument.Load()? ................................................ 36


Page

Q53. What is difference between ADO.NET and LINQ to SQL? ....................................................................... 36


Q54. How can you handle concurrency in LINQ to SQL? ................................................................................. 36
Q55. How can you handle concurrency at field level in LINQ to SQL?............................................................. 37

Other Free E-Books ....................................................................................... 38

8
Page
LINQ
Q1. What is LINQ and why to use it?
Ans. LINQ stands for "Language Integrated Query" and pronounced as "LINK". LINQ was introduced with .NET
Framework 3.5 including Visual Studio 2008, C# 3.0 and VB.NET 2008 (VB 9.0). It enables you to query the data
from the various data sources like SQL databases, XML documents, ADO.NET Datasets, Web services and any other
objects such as Collections, Generics etc. by using a SQL Query like syntax with .NET framework languages like C#
and VB.NET.

Why LINQ

LINQ has full type checking at compile-time and IntelliSense support in Visual Studio, since it used the .NET
framework languages like C# and VB.NET. This powerful feature helps you to avoid run-time errors.

LINQ also provides a uniform programming model (i.e. common query syntax) to query various data sources.
Hence you don’t need to learn the different ways to query different data sources.

Q2. Which namespace is necessary to use LINQ?


Ans. System.Linq namespace is necessary for writing LINQ queries and to implement it.

Q3. What are different flavors of LINQ?


Ans. There are following three flavors of LINQ:

1. LINQ to Objects
It enables you to query any in-memory object like as array, collection and generics types. It offers a new way
to query objects with many powerful features like filtering, ordering and grouping with minimum code.

2. LINQ to ADO.NET
LINQ to ADO.NET is used to query data from different databases like as SQL Server, Oracle, and others. Further,
it can be divided into three flavours:-

I. LINQ to SQL (DLINQ)


It is specifically designed to work with only SQL Server database. It is an object-relational mapping (ORM)
framework that allows 1-1 mapping of SQL Server database to .NET Classes. These classes are
automatically created by the wizard based on database table and we can use these classes immediately.

II. LINQ to Datasets


It is an easy and faster way to query data cached in a Dataset object. This allows you to do further data
manipulation operations (like searching, filtering, sorting) on Dataset using LINQ Syntax. It can be used
9
Page

to query and manipulate any database (like Oracle, MySQL, DB2 etc.) that can be query with ADO.NET.
III. LINQ to Entities
In many ways, it looks like LINQ to SQL. It is an object-relational mapping (ORM) framework that allows
1-1 mapping , 1-many mapping and many-many mapping of a database to .NET Classes. Unlike LINQ to
SQL, it can be used to query any database (like Oracle, MySQL, and DB2 etc.) including SQL Server. Now,
it is called ADO.NET Entity Framework.

3. LINQ to XML (XLINQ)


This allows you to do different operations on XML data source like querying or reading, modifying, manipulating, and
saving changes to XML documents. System.Xml.Linq namespace contains classes for LINQ to XML.

4. Parallel LINQ (PLINQ)


PLINQ was introduced with .NET Framework 4.0. It is a parallel implementation of LINQ to Objects. PLINQ use
the power of parallel programming which targets the Task Parallel Library. PLINQ helps you to write a LINQ
query which will be execute simultaneously or parallel on different processors.

Q4. What are advantages of LINQ?


Ans. There are following advantages of using LINQ:

1. It provides a uniform programming model (i.e. common query syntax) to query data sources (like SQL
databases, XML documents, ADO.NET Datasets, Various Web services and any other objects such as
Collections, Generics etc.)
2. It has full type checking at compile-time and IntelliSense support in Visual Studio. This powerful feature
helps you to avoid run-time errors.
3. It supports various powerful features like filtering, ordering and grouping with minimum code.
4. Its Query can be reused.
5. It also allows debugging through .NET debugger.

Q5. What are disadvantages of LINQ?


Ans. There are following disadvantages of using LINQ:

1. LINQ is not good to write complex queries like SQL.


2. LINQ doesn’t take the full advantage of SQL features like cached execution plan for stored procedure.
3. Performance is degraded if you don't write the LINQ query correctly.
4. If you have done some changes in your query, you have to recompile it and redeploy its dll to the server.

Q6. What are different methods to write LINQ Query?


Ans. There are following three ways to write LINQ Query:

1. Query Expression (Query Syntax)


Query expression syntax is like as SQL query syntax with just a few minor deviations. The result of a query
expression is a query object, which is usually a collection of type IEnumerable<T> or IQueryable<T>. This
10

syntax is easy to read and write and at compile time, query expression is converted into Method
Page

Invocation.
Query Expression Syntax:

from [identifier]
in [source collection]
let [expression]
where [boolean expression]
order by [expression(ascending/descending)]
select [expression]
group [expression] by [expression]
into [expression]

Query Expression Example:

// Datasource
List<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

// Query based syntax


IEnumerable<int> query =
from num in numbers
where num > 5 && num < 10
select num; //result: 6,7,8,9

2. Method Invocation (Method Syntax)


Method syntax is complex as compared to Query expression since it uses lambda expression to write LINQ
query. It is easily understood by .NET CLR. Hence at compile time, Query expression is converted into
Method Invocation. The result of a Method syntax is also a query object, which is usually a collection of
type IEnumerable<T> or IQueryable<T>.

Method Invocation Syntax:

[source collection]
.Where [boolean expression]
.OrderBy [expression(ascending/descending)]
.Select [expression]
.GroupBy [expression]

Method Invocation Example:

// Datasource
List<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

// Method based syntax


IEnumerable<int> query = numbers.Where(num => num > 5 && num < 10);
//result: 6,7,8,9
11

3. Mixed Syntax
Page
You can use a mixture of both syntax by enclosing a query expression inside parentheses and make a call
to method.

// Datasource
List<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

// Mixed syntax
int query = (from num in numbers
where num > 5 && num < 10
select num).Count();
//result: 4

Note: There are no semantic differences (in terms of performance, execution) between Query Syntax and Method
Syntax.

Q7. How var type is different from anonymous type?


Ans. var- var data type was introduced with C# 3.0. It is used to declare implicitly typed local variable means it
tells the compiler to figure out the type of the variable at compile time. A var variable must be initialized at the
time of declaration.

For Example:

var i = 20; // implicitly typed


int i = 20; //explicitly typed

var str = "1"; //declaration and initialization


var num = 0;

string s = "string"; //explicitly typed


var s2 = s; // implicitly typed

Basically, var is an anonymous type, hence use it whenever you don't know the type of output or it is anonymous.
Suppose you are joining two tables and retrieving data from both the tables then the result will be an anonymous
type since data will come from both the tables.

Expression assigned to var must be executed at compile time to know the type of output, so that var type may
behave like the new type assigned to it.

DataContext context = new DataContext();


var q = (from e in context.Employee
join d in context.Department on e.DeptID equals d.DeptID
select new
{
e.EmpID,
e.FirstName,
d.DeptName,
12

d.DeptLocation
});
Page
Anonymous Type- An anonymous type is a simple class generated by the compiler within IL to store a set of values.
var data type and new keyword is used to create an anonymous type.

var emp = new { Name = "Deepak", Address = "Noida", Salary = 21000 };

At compile time, the compiler will create an anonymous type, as follows:

class __Anonymous1
{
private string name;
private string address;
int salary;
public string Name
{
get { return name; }
set { name=value }
}
public string Address
{
get { return address; }
set { address = value; }
}
public int Salary
{
get { return salary; }
set { salary = value; }
}
}

The anonymous type is very useful when you want to shape the result in your desired form like this:

DataContext context = new DataContext();


var result = from book in context.Books
where book.Price > 200
orderby book.IssueDate descending
select new
{
Name = book.Name,
IssueNumber = "#" + book.Issue
};

In above example, I change the name of the “Issue” field of Book table to “IssueNumber” and add # before value
to get desired output.

Q8. What is anonymous method?


Ans. The concept of anonymous method was introduced in C# 2.0. An anonymous method is an inline unnamed
method in the code. It is created using the delegate keyword and doesn’t have its name and return type.
13

In this way, an anonymous method has no name, optional parameters and return type; it has only body. An
Page

anonymous method behaves like a regular method and allows you to write inline code in place of regular method.
class Program
{
//delegate for representing anonymous method
delegate int del(int x, int y);

static void Main(string[] args)


{
//anonymous method using delegate keyword
del d1 = delegate(int x, int y) { return x * y; };

int z1 = d1(2, 3);

Console.WriteLine(z1);
}
}
//output:

Key points about anonymous method

1. A variable, declared outside the anonymous method can be accessed inside the anonymous method.
2. A variable, declared inside the anonymous method can’t be accessed outside the anonymous method.
3. We use anonymous method in event handling.
4. An anonymous method, declared without parenthesis can be assigned to a delegate with any signature.
5. Unsafe code can’t be accessed within an anonymous method.
6. An anonymous method can’t access the ref or out parameters of an outer scope.

Q9. What is lambda expression?


Ans. The concept of lambda expression was introduced in C# 3.0. Typically, lambda expression is a more concise
syntax of anonymous method. It is just a new way to write anonymous method. At compile time all the lambda
expressions are converted into anonymous methods according to lambda expression conversion rules. The left
side of the lambda operator "=>" represents the arguments of anonymous method and the right side represents
the method body.

Lambda expression Syntax

(Input-parameters) => expression-or-statement-block

Types of Lambda expression

1. Statement Lambda -Statement lambda has a statement block on the right side of the lambda operator "=>".

x => { return x * x; };
14

2. Expression Lambda - Expression lambda has only an expression (no return statement or curly braces), on the
right side of the lambda operator "=>".
Page
x => x * x; // here x*x is expression

Anonymous Method and Lambda Expression example:

class Program
{
//delegate for representing anonymous method
delegate int del(int x, int y);

static void Main(string[] args)


{
//anonymous method using expression lambda
del d1 = (x, y) => x * y;
// or (int x, int y) => x * y;

//anonymous method using statement lambda


del d2 = (x, y) => { return x * y; };
// or (int x, int y) => { return x * y; };

//anonymous method using delegate keyword


del d3 = delegate(int x, int y) { return x * y; };

int z1 = d1(2, 3);


int z2 = d2(3, 3);
int z3 = d3(4, 3);

Console.WriteLine(z1);
Console.WriteLine(z2);
Console.WriteLine(z3);
}
}
//output:
6
9
12

Q10. What is Extension method?


Ans. An extension method is a static method of a static class that can be invoked like as an instance method
syntax. Extension methods are used to add new behaviors to an existing type without altering.

In extension method "this" keyword is used with the first parameter and the first parameter will be of type that
is extended by extension method. Other parameters of extensions types can be of any types (data type).

Example:

//defining extension method


public static class MyExtensions
15

{
public static int WordCount(this String str)
Page

{
return str.Split(new char[] { ' ', '.', ',' }).Length;
}
}

class Program
{
public static void Main()
{
string s = "Dot Net Tricks Extension Method Example";

//calling extension method


int i = s.WordCount();

Console.WriteLine(i);
}
}

//output:
//6

Key points about extension method

1. An extension method is defined as static method but it is called like as an instance method.
2. An extension method first parameter specifies the type of the extended object, and it is preceded by the
"this" keyword.
3. An extension method having the same name and signature like as an instance method will never be called
since it has low priority than instance method.
4. An extension method couldn't override the existing instance methods.
5. An extension method cannot be used with fields, properties or events.
6. The compiler doesn't cause an error if two extension methods with same name and signature are defined in
two different namespaces and these namespaces are included in same class file using directives. Compiler
will cause an error if you will try to call one of them extension method.

Free download this complete book by using given link

https://goo.gl/DDPHfl
16
Page

You might also like