Linq PDF
Linq PDF
Linq PDF
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.
3
Page
About the Author
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.
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
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.
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:-
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.
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.
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]
// Datasource
List<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
[source collection]
.Where [boolean expression]
.OrderBy [expression(ascending/descending)]
.Select [expression]
.GroupBy [expression]
// Datasource
List<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
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.
For Example:
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.
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.
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:
In above example, I change the name of the “Issue” field of Book table to “IssueNumber” and add # before value
to get desired output.
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);
Console.WriteLine(z1);
}
}
//output:
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.
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
class Program
{
//delegate for representing anonymous method
delegate int del(int x, int y);
Console.WriteLine(z1);
Console.WriteLine(z2);
Console.WriteLine(z3);
}
}
//output:
6
9
12
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:
{
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";
Console.WriteLine(i);
}
}
//output:
//6
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.
https://goo.gl/DDPHfl
16
Page