SlideShare a Scribd company logo
LINQ By PranayRanaBlog : http://pranayamr.blogspot.comTwitter : http://twitter.com/pranayamrFaceBook : http://www.facebook.com/pages/GMind-Solution
OverviewImplicitly typed local variables Anonymous TypesObject and Collection InitializationExtension MethodLambda ExpressionLinq
Virtual DiagramLINQAnonymosTypesImplicitly typed local variables  Extension  MethodObject and Collection InitializationLambda Expression
Implicitly typed local variablesSyntaxvar i = 5;var s = "Hello";var d = 1.0;var numbers = new int[] {1, 2, 3};var orders = new  Easy to use
No need to define type RestrictionsThe declarator must include an initializer.The initializer must be an expression. The initializer cannot be an object or collection initializer by itself, but it can be a new expression that includes an object or collection initializer.The compile-time type of the initializer expression cannot be the null type.If the local variable declaration includes multiple declarators, the initializers must all have the same compile-time type.
var x; // Error, no initializer to infer type fromvar y = {1, 2, 3}; // Error, collection initializer not permittedvar z = null; // Error, null type not permitted
Anonymous TypesWhat is Anonymous types ?Create new types without defining itHow to define Anonymous types ?var pranay = new { id=1, Name= "pranay rana" };var krunal = new { id=1, Name= "krunal mevada" };Use of itvar user = from user in Users  select new { user.Name, user.Id};
Object and Collection InitializationWhat is object Initialization ?create object without writing too much lengthy code and without invoking constructor.Exampleclass Employee{  public string Name { get; set; }  public string Address { get; set; }  public Employee(){} public Employee (string name) { Name= name;  }}
Employee emp = new Employee() { Name="Pranay", Address="Ahmedabad"  };orEmployee emp = new Employee("Hemang") { Address="Ahmedabad"   };
Collection InitializationList<Employee> emp = new List<Employee>      {         new Employee { Name="Pranay",                                          Address="Ahmedabad"  },         new Employee { Name="Krunal",Address="Mevada"  },         null     };
Extension MethodWhat is Extesion Methods ?Allow programmer to "add" methods to existing types without creating a new derived type, recompiling, or by modifying the original typeExamplepublic static class Utilities{    public static string encryptString(this string str)    {           System.Security.Cryptography.MD5CryptoServiceProvider x =                         new      System.Security.Cryptography.MD5CryptoServiceProvider();           byte[] data = System.Text.Encoding.ASCII.GetBytes(str);           data = x.ComputeHash(data);           return System.Text.Encoding.ASCII.GetString(data);     }}
Linq
Lambda ExpressionReplacement of the anonymous method available in C#2.0Consist of single line or block of statement=> is lamda expression operatorSyntax( param ) => expr(int x) = > { return x + 1 };param => exprx=> x + 1;
Use of Lambda expressionC#2.0 by using anonymous method    List<int> even =        lstNumber.FindAll( delegate(inti) { if(i%2==)                                                                   return i; }But for the C#3.0 with the lambda expression it will      List<int> even           = lstNumber.FindAll( i => (i%2) ==0 }In LINQvar order = orders.where( o=> o.ProcessStatus  = ProcessStatus.Completed);
What is orm ?Object Relational Mapping Allow to map your database structure with the business layer model Hide low level database interaction detailsMake development easy and faster
LINQWhat is LINQ ?Language-Integrated Query Made up to make query any source of dataSome flavor of LINQLINQ to Object {Queries performed against the in-memory data}LINQ to SQL (formerly DLinq) {Queries performed against the relation database only Microsoft SQL Server Supported}LINQ to DataSet {Supports queries by using ADO.NET data sets and data tables}LINQ to Entities {Microsoft ORM solution}LINQ to XML (formerly XLinq) { Queries performed against the XML source}
Linq
SelectSQLSELECT * FROM [User]LINQ
var user = from u in Users select u;
Select with ColumnsSQL Select FirstName, LastName from [User]LINQfrom u in Users select new { u.FirstName, u.LastName };
Linq
Filter Selected DataSQLSelect firstname,LastName from [User] where id = 3LINQfrom u in Users where u.Id ==3select new { u.FirstName, u.LastName };
Linq
Filtering String DataSQLSELECT [Id], [FirstName], [LastName], [Email], [DisplayName], [Address1], [Address2], [Password], [Role] FROM [User] WHERE [Email] LIKE '%pranay%'LINQ    from u in Users where u.Email.Contains ("pranay") select u;Or    from u in Users where u.Email.StartsWith ("pranay") select u;
Linq
Inner JoinSQLSELECT [User].[Id], [FirstName], [LastName], [UserId], [MobileNo] FROM [User] INNER JOIN [UserClients] ON [User].[id] = [UserId]LINQvar user = from u in Users     join uc in UserClients on u.Id equals uc.UserId select new     { u.Id, u.FirstName, u.LastName, uc.MobileNo,   uc.imeiNO, uc.Id,     };
Linq
Outer JoinSQLSELECT [t0].[Id], [FirstName], [LastName], [UserId] AS [UserId], [MobileNo] AS [MobileNo] FROM [User] AS [t0] LEFT OUTER JOIN [UserClients] ON ([t0].[id]) = [UserId]LINQvar user = from u in Users join uc in UserClients on u.Id equals uc.UserId into myuserwithclient from m in myuserwithclient.DefaultIfEmpty() select new { u.Id, u.FirstName, u.LastName, m.UserId, m.MobileNo };
Linq
Ordering DataSQLSelect * from [User] order by firstNameLINQvar user = from u in Usersorderbyu.FirstNameselect new    { u.FirstName, u.LastName };More than one columnvaremp = from e in dc.Employeesorderbye.Name, e.Desc select e;
Linq
Grouping DataSQLSELECT COUNT(*) AS [test], [UserId] FROM [UserClients] GROUP BY [UserId]LINQvar user = from u in UserClients  group u by u.UserId   into c   select new    { t1 = c.Key, tcount = c.Count() };
Linq
Filter Data Using IN and NOT IN ClausesSQLSELECT [Id], [UserId], [IMEINo] FROM [UserClients] WHERE [UserId] IN (3, 4)LINQint[] chosenOnes = { 3, 4 };var user = from u in UserClients             where chosenOnes.Contains(u.UserId.Value)              select new               { u.id,u.userid, u.ImeiNo};
Linq
Filtering Data by Row NumbersSQLSELECT * FROM ( SELECT ROW_NUMBER() OVER (ORDER BY [id]) AS [ROW_NUMBER], [id], [FirstName], [LastName], [Email], [DisplayName], [Address1], [Address2], [Password], [Role] FROM [User] AS [t0] ) AS [t1] WHERE [t1].[ROW_NUMBER] BETWEEN 11 AND 20 ORDER BY [t1].[ROW_NUMBER]LINQvar users = from u in Users select u; varfilterUsers= users.OrderBy (p => p.Id).Skip (10).Take(10);
Linq
SQL ISNULL functionLINQvar user = from u in Users join uc in UserClients on u.Id equals uc.UserId into myuserwithclient from m in myuserwithclient.DefaultIfEmpty() select new { u.Id, FirstName= u.FirstName, LastName= u.LastName, UserId= m.UserId, MobileNo= m.MobileNo?? "N/A" };
SelectmanyFlattens the resulting sequences into one sequenceusers.SelectMany (      u => u.Userclient,       (u, uc) =>          new          {            Name = u.Name,             Mobileno = uc.Mobile,             IsApproved = uc.IsApproved         }   )
Linq Deferred ExecutionQuery not going to execute at this point   var query =        from customer in db.Customers where  customer.City == "Paris" select customer; Query get executed when we apply method like (Count(),toList() etc.)int count =   (from customer in db.Customers where   customer.City == "Paris" select customer).Count();
Questions and Query
Thank YOU

More Related Content

PPTX
Linq Introduction
PPT
JavaScript Objects
PPT
Linq And Its Impact On The.Net Framework
ODP
Functions & closures
ODP
Xml processing in scala
ODP
Functional programming with Scala
PPT
Javascript built in String Functions
PPTX
Javascript
Linq Introduction
JavaScript Objects
Linq And Its Impact On The.Net Framework
Functions & closures
Xml processing in scala
Functional programming with Scala
Javascript built in String Functions
Javascript

What's hot (20)

PPTX
Python dictionary
PPTX
11. session 11 functions and objects
PPTX
PPT
Object oriented programming using c++
PPTX
Functional Programming with C#
ODP
Pattern Matching - at a glance
PPT
C++ oop
PPTX
Object oriented programming in C++
PPT
XPath Injection
PDF
NLJUG University Sessie: Java Reborn, Powered by Ordina
PPTX
How to extract domain name from email address
PPTX
XML & XPath Injections
PPTX
Breaking down data silos with the open data protocol
PDF
Hacking XPATH 2.0
PDF
JavaScript - Chapter 10 - Strings and Arrays
PPTX
Chapter 16 Dictionaries
PPT
Chapter 2 - Getting Started with Java
PPTX
Java Foundations: Methods
PDF
Types in JavaScript: why you should care
PPT
Core java by a introduction sandesh sharma
Python dictionary
11. session 11 functions and objects
Object oriented programming using c++
Functional Programming with C#
Pattern Matching - at a glance
C++ oop
Object oriented programming in C++
XPath Injection
NLJUG University Sessie: Java Reborn, Powered by Ordina
How to extract domain name from email address
XML & XPath Injections
Breaking down data silos with the open data protocol
Hacking XPATH 2.0
JavaScript - Chapter 10 - Strings and Arrays
Chapter 16 Dictionaries
Chapter 2 - Getting Started with Java
Java Foundations: Methods
Types in JavaScript: why you should care
Core java by a introduction sandesh sharma
Ad

Viewers also liked (20)

PPTX
Linq to entity
PPT
Linq e Ef
PPTX
LINQ for absolute beginners
PPT
Ling to SQL and Entity Framework performance analysis
PPT
B_110500002
PPT
20130329 introduction to linq
PPT
Linq intro
PPTX
Entity Framework - Queries
PPTX
Entity framework
KEY
The Entity Data Model
PPTX
Entity Framework - Entity Data Model (edm)
PPTX
LINQ and LINQPad
PPTX
Think in linq
PPTX
PostCss
PPTX
メタプログラミング C#
PPTX
C# 式木 (Expression Tree) ~ LINQをより深く理解するために ~
PPTX
LINQ in C#
PPT
LINQ 2 SQL Presentation To Palmchip And Trg, Technology Resource Group
PPT
Linq to entity
Linq e Ef
LINQ for absolute beginners
Ling to SQL and Entity Framework performance analysis
B_110500002
20130329 introduction to linq
Linq intro
Entity Framework - Queries
Entity framework
The Entity Data Model
Entity Framework - Entity Data Model (edm)
LINQ and LINQPad
Think in linq
PostCss
メタプログラミング C#
C# 式木 (Expression Tree) ~ LINQをより深く理解するために ~
LINQ in C#
LINQ 2 SQL Presentation To Palmchip And Trg, Technology Resource Group
Ad

Similar to Linq (20)

PPT
PostThis
PPT
PPT
Linq in C# 3.0: An Overview
PPT
Linq 090701233237 Phpapp01
PPT
Linq
PPT
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
PPT
Of Lambdas and LINQ
PPT
Introduction to Linq
PPT
PPT
Whats New In C# 3.0
PPT
Language Integrated Query By Nyros Developer
PPT
Daniel Egan Msdn Tech Days Oc Day2
PPT
Understanding linq
PPTX
Linq Sanjay Vyas
PPT
Linq
PPT
Linq
PPT
Mixing functional and object oriented approaches to programming in C#
PDF
Litwin linq
PPT
Linq 1224887336792847 9
PPT
Linq To The Enterprise
PostThis
Linq in C# 3.0: An Overview
Linq 090701233237 Phpapp01
Linq
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
Of Lambdas and LINQ
Introduction to Linq
Whats New In C# 3.0
Language Integrated Query By Nyros Developer
Daniel Egan Msdn Tech Days Oc Day2
Understanding linq
Linq Sanjay Vyas
Linq
Linq
Mixing functional and object oriented approaches to programming in C#
Litwin linq
Linq 1224887336792847 9
Linq To The Enterprise

Recently uploaded (20)

PDF
Architecture types and enterprise applications.pdf
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
Tartificialntelligence_presentation.pptx
PDF
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PPTX
OMC Textile Division Presentation 2021.pptx
PDF
Hybrid model detection and classification of lung cancer
PDF
Web App vs Mobile App What Should You Build First.pdf
PDF
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
PPTX
The various Industrial Revolutions .pptx
PDF
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
PDF
A novel scalable deep ensemble learning framework for big data classification...
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PPTX
cloud_computing_Infrastucture_as_cloud_p
PDF
A comparative study of natural language inference in Swahili using monolingua...
PDF
NewMind AI Weekly Chronicles – August ’25 Week III
PPTX
1. Introduction to Computer Programming.pptx
PPTX
Final SEM Unit 1 for mit wpu at pune .pptx
PDF
STKI Israel Market Study 2025 version august
PDF
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
Architecture types and enterprise applications.pdf
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Tartificialntelligence_presentation.pptx
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
Assigned Numbers - 2025 - Bluetooth® Document
OMC Textile Division Presentation 2021.pptx
Hybrid model detection and classification of lung cancer
Web App vs Mobile App What Should You Build First.pdf
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
The various Industrial Revolutions .pptx
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
A novel scalable deep ensemble learning framework for big data classification...
Group 1 Presentation -Planning and Decision Making .pptx
cloud_computing_Infrastucture_as_cloud_p
A comparative study of natural language inference in Swahili using monolingua...
NewMind AI Weekly Chronicles – August ’25 Week III
1. Introduction to Computer Programming.pptx
Final SEM Unit 1 for mit wpu at pune .pptx
STKI Israel Market Study 2025 version august
From MVP to Full-Scale Product A Startup’s Software Journey.pdf

Linq

  • 1. LINQ By PranayRanaBlog : http://pranayamr.blogspot.comTwitter : http://twitter.com/pranayamrFaceBook : http://www.facebook.com/pages/GMind-Solution
  • 2. OverviewImplicitly typed local variables Anonymous TypesObject and Collection InitializationExtension MethodLambda ExpressionLinq
  • 3. Virtual DiagramLINQAnonymosTypesImplicitly typed local variables Extension MethodObject and Collection InitializationLambda Expression
  • 4. Implicitly typed local variablesSyntaxvar i = 5;var s = "Hello";var d = 1.0;var numbers = new int[] {1, 2, 3};var orders = new Easy to use
  • 5. No need to define type RestrictionsThe declarator must include an initializer.The initializer must be an expression. The initializer cannot be an object or collection initializer by itself, but it can be a new expression that includes an object or collection initializer.The compile-time type of the initializer expression cannot be the null type.If the local variable declaration includes multiple declarators, the initializers must all have the same compile-time type.
  • 6. var x; // Error, no initializer to infer type fromvar y = {1, 2, 3}; // Error, collection initializer not permittedvar z = null; // Error, null type not permitted
  • 7. Anonymous TypesWhat is Anonymous types ?Create new types without defining itHow to define Anonymous types ?var pranay = new { id=1, Name= "pranay rana" };var krunal = new { id=1, Name= "krunal mevada" };Use of itvar user = from user in Users  select new { user.Name, user.Id};
  • 8. Object and Collection InitializationWhat is object Initialization ?create object without writing too much lengthy code and without invoking constructor.Exampleclass Employee{  public string Name { get; set; }  public string Address { get; set; }  public Employee(){} public Employee (string name) { Name= name;  }}
  • 9. Employee emp = new Employee() { Name="Pranay", Address="Ahmedabad"  };orEmployee emp = new Employee("Hemang") { Address="Ahmedabad"   };
  • 10. Collection InitializationList<Employee> emp = new List<Employee>      {         new Employee { Name="Pranay", Address="Ahmedabad"  },         new Employee { Name="Krunal",Address="Mevada"  },         null     };
  • 11. Extension MethodWhat is Extesion Methods ?Allow programmer to "add" methods to existing types without creating a new derived type, recompiling, or by modifying the original typeExamplepublic static class Utilities{    public static string encryptString(this string str)    {           System.Security.Cryptography.MD5CryptoServiceProvider x = new      System.Security.Cryptography.MD5CryptoServiceProvider();           byte[] data = System.Text.Encoding.ASCII.GetBytes(str);           data = x.ComputeHash(data);           return System.Text.Encoding.ASCII.GetString(data);     }}
  • 13. Lambda ExpressionReplacement of the anonymous method available in C#2.0Consist of single line or block of statement=> is lamda expression operatorSyntax( param ) => expr(int x) = > { return x + 1 };param => exprx=> x + 1;
  • 14. Use of Lambda expressionC#2.0 by using anonymous method List<int> even =      lstNumber.FindAll( delegate(inti) { if(i%2==) return i; }But for the C#3.0 with the lambda expression it will List<int> even      = lstNumber.FindAll( i => (i%2) ==0 }In LINQvar order = orders.where( o=> o.ProcessStatus  = ProcessStatus.Completed);
  • 15. What is orm ?Object Relational Mapping Allow to map your database structure with the business layer model Hide low level database interaction detailsMake development easy and faster
  • 16. LINQWhat is LINQ ?Language-Integrated Query Made up to make query any source of dataSome flavor of LINQLINQ to Object {Queries performed against the in-memory data}LINQ to SQL (formerly DLinq) {Queries performed against the relation database only Microsoft SQL Server Supported}LINQ to DataSet {Supports queries by using ADO.NET data sets and data tables}LINQ to Entities {Microsoft ORM solution}LINQ to XML (formerly XLinq) { Queries performed against the XML source}
  • 19. var user = from u in Users select u;
  • 20. Select with ColumnsSQL Select FirstName, LastName from [User]LINQfrom u in Users select new { u.FirstName, u.LastName };
  • 22. Filter Selected DataSQLSelect firstname,LastName from [User] where id = 3LINQfrom u in Users where u.Id ==3select new { u.FirstName, u.LastName };
  • 24. Filtering String DataSQLSELECT [Id], [FirstName], [LastName], [Email], [DisplayName], [Address1], [Address2], [Password], [Role] FROM [User] WHERE [Email] LIKE '%pranay%'LINQ from u in Users where u.Email.Contains ("pranay") select u;Or from u in Users where u.Email.StartsWith ("pranay") select u;
  • 26. Inner JoinSQLSELECT [User].[Id], [FirstName], [LastName], [UserId], [MobileNo] FROM [User] INNER JOIN [UserClients] ON [User].[id] = [UserId]LINQvar user = from u in Users join uc in UserClients on u.Id equals uc.UserId select new { u.Id, u.FirstName, u.LastName, uc.MobileNo, uc.imeiNO, uc.Id, };
  • 28. Outer JoinSQLSELECT [t0].[Id], [FirstName], [LastName], [UserId] AS [UserId], [MobileNo] AS [MobileNo] FROM [User] AS [t0] LEFT OUTER JOIN [UserClients] ON ([t0].[id]) = [UserId]LINQvar user = from u in Users join uc in UserClients on u.Id equals uc.UserId into myuserwithclient from m in myuserwithclient.DefaultIfEmpty() select new { u.Id, u.FirstName, u.LastName, m.UserId, m.MobileNo };
  • 30. Ordering DataSQLSelect * from [User] order by firstNameLINQvar user = from u in Usersorderbyu.FirstNameselect new { u.FirstName, u.LastName };More than one columnvaremp = from e in dc.Employeesorderbye.Name, e.Desc select e;
  • 32. Grouping DataSQLSELECT COUNT(*) AS [test], [UserId] FROM [UserClients] GROUP BY [UserId]LINQvar user = from u in UserClients group u by u.UserId into c select new { t1 = c.Key, tcount = c.Count() };
  • 34. Filter Data Using IN and NOT IN ClausesSQLSELECT [Id], [UserId], [IMEINo] FROM [UserClients] WHERE [UserId] IN (3, 4)LINQint[] chosenOnes = { 3, 4 };var user = from u in UserClients where chosenOnes.Contains(u.UserId.Value) select new { u.id,u.userid, u.ImeiNo};
  • 36. Filtering Data by Row NumbersSQLSELECT * FROM ( SELECT ROW_NUMBER() OVER (ORDER BY [id]) AS [ROW_NUMBER], [id], [FirstName], [LastName], [Email], [DisplayName], [Address1], [Address2], [Password], [Role] FROM [User] AS [t0] ) AS [t1] WHERE [t1].[ROW_NUMBER] BETWEEN 11 AND 20 ORDER BY [t1].[ROW_NUMBER]LINQvar users = from u in Users select u; varfilterUsers= users.OrderBy (p => p.Id).Skip (10).Take(10);
  • 38. SQL ISNULL functionLINQvar user = from u in Users join uc in UserClients on u.Id equals uc.UserId into myuserwithclient from m in myuserwithclient.DefaultIfEmpty() select new { u.Id, FirstName= u.FirstName, LastName= u.LastName, UserId= m.UserId, MobileNo= m.MobileNo?? "N/A" };
  • 39. SelectmanyFlattens the resulting sequences into one sequenceusers.SelectMany (      u => u.Userclient,       (u, uc) =>          new          {            Name = u.Name,             Mobileno = uc.Mobile,             IsApproved = uc.IsApproved         }   )
  • 40. Linq Deferred ExecutionQuery not going to execute at this point var query = from customer in db.Customers where customer.City == "Paris" select customer; Query get executed when we apply method like (Count(),toList() etc.)int count = (from customer in db.Customers where customer.City == "Paris" select customer).Count();