linq (1)

32
LINQ Copyright © 2015 Pratian Technologies www.pratian.com Unit 12 Linq LINQ

Upload: samarjeet-saurabh

Post on 07-Aug-2015

43 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Linq (1)

LINQ Copyright © 2015 Pratian Technologies

www.pratian.com

Unit 12 – Linq

LINQ

Page 2: Linq (1)

LINQ Copyright © 2015 Pratian Technologies

www.pratian.com

Unit 12 – Linq

Objectives

Introduction to LINQ

LINQ

LINQ

LINQ

LINQ

LINQ

LINQ

architecture

query syntax (using lambda

standard Query operators

to Object

to datasets to SQL

expression and comprehension syntax)

Understand LINQ to XML

Page 3: Linq (1)

LINQ Copyright © 2015 Pratian Technologies

www.pratian.com

Unit 12 – Linq

Current Scenario

• Accessing Different Data Sources.

• Today, data managed by a program can belong to different data domains:

• Example an array, an object graph, an XML document, a database, a text

file, a registry key, an e-mail message, Simple Object Access Protocol

(SOAP) message content, a Microsoft Office Excel file etc.

• Each data domain has its own specific API’s for accessing data,

To query RDBDMS-SQL is used or

To navigate XML data with Document Object Model (DOM) etc

• If the data model is not tied to the language, it requires managing different

type systems between data sources and Programming language.

How can you resolve this “impedance mismatch” between data sources and

Programming Languages and as well as providing a single querying

interface for a multitude of data sources - using LINQ

Page 4: Linq (1)

LINQ Copyright © 2015 Pratian Technologies

www.pratian.com

Unit 12 – Linq

LINQ –Language Integrated Query

• What?

Offers a uniform way to access and manage data independent of data sources.

Is a general purpose query facilities to the .NET Framework that apply to all

sources of information, not just relational or XML data. This facility is called .NET

Language Integrated Query (LINQ).

It enables you to query and manipulate data with a consistent model that is

independent from data sources.

Extends powerful query capabilities to CLR languages like C#, VB.NET

• Why?

Language Integration

Type Checking

Standard Query Operators

Can access any data –Collections, Relational and XML, directory structures

• How?

• By using LINQ classes System.Linq , System.Data.Linq and System.Xml.Linq.

Page 5: Linq (1)

LINQ Copyright © 2015 Pratian Technologies

www.pratian.com

Unit 12 – Linq

Understanding LINQ Architecture

[ ]

J

] )

Query

(

( CI [ others ... VB

.Net --

.ngu.g. Integrated

(UNQ)

XMIL

Page 6: Linq (1)

LINQ Copyright © 2015 Pratian Technologies

www.pratian.com

Unit 12 – Linq

]

LINQ Query Syntax Zero or more from, join, let, where, or orderby

Starts with from

Ends with select or group by

LINQ Query Example

var contacts =

from c in customers

where c.City == "Hove"

select new { c.Name, c.Phone };

from id in source

join id in source on expr equals expr

where condition

orderby ordering, ordering, … }

select expr | group expr by key

[into id query

Optional into continuation

Page 7: Linq (1)

LINQ Copyright © 2015 Pratian Technologies

www.pratian.com

Unit 12 – Linq

Writing LINQ Query Expressions

Comprehension Syntax Comprehension Syntax :

Lambda expressio

ns Lambda Syntax :

Extension methods Object

initializes

Anonymous types

var contacts = customers

.Where(c => c.City == "Hove")

.Select(c => new { c.Name, c.Phone });

var contacts = from c in customers

where c.City == "Hove"

select new { c.Name, c.Phone };

LINQ query expressions can be written using Comprehension syntax and Lambda

expressions

Page 8: Linq (1)

LINQ Copyright © 2015 Pratian Technologies

www.pratian.com

Unit 12 – Linq

Standard Query Operators

• LINQ provides a set of Operators to query data from data sources–Query

Operators

These operators are called as Standard Query Operators.

The standard query operators are defined using static Enumerable and

Queryable classes from the System.Linq namespace

Using these operators; we could Filter, Project, Join, Order, Group data in

LINQ query.

Standard Query Operators are classified into Restriction Operators,

Partitioning operators, Concatenation Operators, Join operators, Ordering

operators, Set Operators, Grouping operators, Quantifiers, Conversion

operators, Element operators, Aggregate operators.

8

Page 9: Linq (1)

LINQ Copyright © 2015 Pratian Technologies

www.pratian.com

Unit 12 – Linq

LINQ Standard Query Operators

Functionality LINQ Standard Query Operators

Restriction Where

Projection Select, SelectMany

Ordering OrderBy, ThenBy

Grouping GroupBy

Quantifiers Any, All

Partitioning Take, Skip, TakeWhile, SkipWhile

Sets Distinct, Union, Intersect, Except

Elements First, FirstOrDefault, ElementAt

Aggregation Count, Sum, Min, Max, Average

Page 10: Linq (1)

LINQ Copyright © 2015 Pratian Technologies

www.pratian.com

Unit 12 – Linq

Projection with Restriction Operator :

Example

10

The above query is equivalent to following Lambda Expression: var mResult= games.Select(g => g). Where(g => g.Price < 20);

IEnumerable<string> mGamelist = from g in games where g.Price < 20

select g;

foreach (string s in gamelist) {

Console.WriteLine(“Games: {0}", s); }

The Select operator projects values from a single sequence or collection and restriction operator helps to filter the values. These operator returns an enumerable object. When the object is enumerated, it produces each element in the selected results.

Example: Write a query to return all those with price less than 20.

Page 11: Linq (1)

LINQ Copyright © 2015 Pratian Technologies

www.pratian.com

Unit 12 – Linq

Order By Operator: Example

11

The Lambda equivalent of the above query is : var subset = games.Where(game => game.Length > 7).

OrderBy(game => game).Select(game => game);

string[] games = { “Car Race", “San Adrias", “V City", "The Darkness", “Mission I", “Rescue Operations" }; var subset = from g in games where g.Length > 7 orderby g select g;

foreach (var game in subset){ Console.WriteLine(game);

}

The Order By operator helps sorting the values in an ascending order. The sorting operators—OrderBy, OrderByDescending, ThenBy, ThenByDescending, and Reverse— provide the capability to sort the results in an ascending or descending manner

Example : To find out games with size larger than 7 and sort them as well.

Page 12: Linq (1)

LINQ Copyright © 2015 Pratian Technologies

www.pratian.com

Unit 12 – Linq

OrderByDescending: Example

12

The Lambda equivalent of the above query is : var query = contact.Select(c => {c.FirstName, c.LastName, c.EmailAddress} ).Where(c => c.FirstName.StartsWith("S")).OrderByDescending(c => c.FirstName);

IEnumerable<string> query =from c in contact where c.FirstName.StartsWith("S") orderby c.LastName descending select new {c.FirstName, c.LastName, c.EmailAddress}

The OrderByDescending operator sorts the resulting values of the sequence in descending order Example : The following shows how to sort a sequence in descending order

Page 13: Linq (1)

LINQ Copyright © 2015 Pratian Technologies

www.pratian.com

Unit 12 – Linq

Grouping Operator: Example

13

List<int> numbers = new List<int>() { 5, 22, 10, 44, 4340, 15, 991, 57, 68, 87 }; IEnumerable<IGrouping<int, int>> query = from number in numbers

group number by number % 2; foreach (var group in query) { Console.WriteLine(group.Key == 0 ? "\nEven numbers:" : "\nOdd numbers:"); foreach (int i in group)

Console.WriteLine(i); }

Grouping is the concept of grouping the values or elements of a sequence according to a specified value (selector). LINQ contains a single grouping operator, GroupBy. It groups elements that share a common attribute. Each group is represented by an IGrouping<TKey, TElement> object. Example : The following shows how to group all the even elements in the List<> collection

Page 14: Linq (1)

LINQ Copyright © 2015 Pratian Technologies

www.pratian.com

Unit 12 – Linq

Aggregating Operators: Example

14

The Lambda equivalent of the above query is : var highTemp = (from p in temperatures select p).Max();

double[] temperatures = { 28.0, 19.5, 32.3, 33.6, 26.5, 29.7 }; double maxTemp = temperatures.Max(); Console.WriteLine(maxTemp)

Aggregate functions perform calculations on a set of values and return a single value, such as performing a sum or average of values of a given elements. There are few LINQ aggregate query operators: Aggregate, Average, Count, Max, Min, and Sum. Example : The following shows how to use aggregate operator

Page 15: Linq (1)

LINQ Copyright © 2015 Pratian Technologies

www.pratian.com

Unit 12 – Linq

What is LINQ-to-Objects? • What ?

It represents a new approach to query collections over traditional foreach iterate.

Provides a facility to write queries against generic or non-generic in-memory

collections.

It allows to query any enumerable collections such as Array ArrayList, List<T>, or

Dictionary<TKey, Tvalue>.

• Why ?

Normally for retrieving data from a collection complex foreach loops are used.

In the LINQ approach, uses a declarative code that describes what is to be

retrieved.

It provides powerful filtering, ordering, and grouping capabilities with a minimum of

application code.

• How ?

• Use of LINQ queries with any IEnumerable or IEnumerable<T>

collection directly, without the use of an intermediate LINQ provider API.

Page 16: Linq (1)

LINQ Copyright © 2015 Pratian Technologies

www.pratian.com

Unit 12 – Linq

LINQ-to-Objects –Example

LINQ query expression

LINQ To Object

Page 17: Linq (1)

LINQ Copyright © 2015 Pratian Technologies

www.pratian.com

Unit 12 – Linq

Querying Non Generic Collections Using LINQ

LINQ query Expressions

Result

var t = from BookInformation bks in arrlist where

bks.Title.Contains("LINQ") select bks;

var titles = from book in arrlist.Cast<BookInformation>() where book.Title.Contains("LINQ") select book ;

ArrayList arrlist = new ArrayList(); arrlist.Add(new BookInformation {Title="ASP.Net 3.5",Author="ABC", Price=645 }); arrlist.Add(new BookInformation { Title = "LINQ Bible", Author = "Anna", Price = 450

}); arrlist.Add(new BookInformation { Title = "LINQ Guide", Author = "Mathews", Price

= 300 }); arrlist.Add(new BookInformation { Title = "LINQ with ASP.Net", Author = "Fedrick", Price = 275 });

Page 18: Linq (1)

LINQ Copyright © 2015 Pratian Technologies

www.pratian.com

Unit 12 – Linq

Querying Generic Collections Using LINQ

Result

where student.Scores[0] > 95

Querying List<T> Using LINQ Adds Object values to ComboBox

var query = from student in arrList

select student;

foreach (Student s in query) { cmbStudents.Items.Add( s.FirstName + " " + s.LastName + ": " + s.Scores[0]); }

List<Student> arrList = new List<Student>();

arrList.Add( new Student {

FirstName = "Anna", LastName = "Houston", Scores = new int[ ] { 98, 92, 81, 60 } }); arrList.Add( new Student { FirstName = "Daniel",LastName = "Demello", Scores = new int[ ] { 75, 84, 91, 39 } });

…………

Page 19: Linq (1)

LINQ Copyright © 2015 Pratian Technologies

www.pratian.com

Unit 12 – Linq

What are LINQ to ADO. Net Technologies ?

There are three separate ADO.NET Language-Integrated Query (LINQ)

technologies:

• LINQ to DataSet :

• LINQ to DataSet Provides richer, optimized query facility for the DataSet.

• LINQ to SQL

• .NET Language Integrated query for Relational data - allows to query

and modify data in SQL Server specific database schemas.

• LINQ to Entities

• LINQ to Entities is a query facility to manage/read data using Entity

Data Model.

Page 20: Linq (1)

LINQ Copyright © 2015 Pratian Technologies

www.pratian.com

Unit 12 – Linq

What is LINQ to SQL ?

• What ?

The technology to access SQL Server specific databases.

Manages relational data as objects –(ORM-Object Relational Mapping)

Enables developers to generate .NET Framework classes (Entity Classes)

that map directly to database tables, views, stored procedures, and user-

defined functions.

It translates into SQL the language-integrated queries in the object model

and sends them to the database for execution. When the database returns

the results, LINQ to SQL translates them back to objects that you can work

with in your own programming language. It uses DataContext Object

• Why ?

• There is a huge divide between modern programming languages and databases in how they represent and manipulate information.

• How?

• Using LINQ to SQL , Entity classes and DataContext generated when .dbml files are created in VS.NET

Page 21: Linq (1)

LINQ Copyright © 2015 Pratian Technologies

www.pratian.com

Unit 12 – Linq

Data Access using LINQ to SQL

Writing Query expressions

DataContext Class

Entity Class LINQ to SQL Classes. (.dbml file) Result

LINQ Query expressions

Page 22: Linq (1)

LINQ Copyright © 2015 Pratian Technologies

www.pratian.com

Unit 12 – Linq

Methods For Data Modification Using LINQ to SQL

• Inserting Row :

InsertOnSubmit () from System.Data.Linq.Table<TEntity> and

SubmitChanges() from DataContext class

• Modifying Row :

• SubmitChanges() from DataContext class

• Deleting Row :

DeletOnSubmit () from System.Data.Linq.Table<TEntity> and

SubmitChanges() from DataContext class

Page 23: Linq (1)

LINQ Copyright © 2015 Pratian Technologies

www.pratian.com

Unit 12 – Linq

CRUD operations using LINQ to SQL

Inserting a row using LINQ to SQL

Page 24: Linq (1)

LINQ Copyright © 2015 Pratian Technologies

www.pratian.com

Unit 12 – Linq

CRUD operations using LINQ to SQL

Modifying a row using LINQ to SQL

Page 25: Linq (1)

LINQ Copyright © 2015 Pratian Technologies

www.pratian.com

Unit 12 – Linq

CRUD operations using LINQ to SQL

Deleting a row using LINQ to SQL

Page 26: Linq (1)

LINQ Copyright © 2015 Pratian Technologies

www.pratian.com

Unit 12 – Linq

What is LINQ to Dataset ?

• What ?

• It simplifies querying by enabling developers to write queries from the CLR languages

like VB.Net and C#.

Can also be used to query over data that has been merged from one or more data

sources and not just SQL Server unlike LINQ to SQL.

It builds on and uses the existing ADO.NET 2.0 architecture.

• Why ?

• The DataSet has limited query capabilities.

• The Select method can be used for filtering and sorting, and the GetChildRows

and GetParentRow methods can be used for hierarchy navigation.

• For more complex queries, however, the developer must write a custom query. This

can result in applications that perform poorly and are difficult to maintain.

• How?

Load the data into the datasets and

Querying an enumeration of DataRow objects,

Page 27: Linq (1)

LINQ Copyright © 2015 Pratian Technologies

www.pratian.com

Unit 12 – Linq

LINQ to Dataset - Example

Page 28: Linq (1)

LINQ Copyright © 2015 Pratian Technologies

www.pratian.com

Unit 12 – Linq

What is LINQ to XML –XLINQ ?

• What ?

API to work with XML in .NET with the power of LINQ.

It provides functionality to read, write, and manipulate XML data.

It is a cleaner, simpler, smaller and faster XML API.

• Why ?

• XLINQ provides the query and transformation power of XQuery and XPath integrated into .NET Framework languages that implement the LINQ pattern

(e.g., C#, VB, etc.).

It takes advantage of standard query operators and adds query extensions

specific to XML.

It provides the in-memory document modification capabilities of the

Document Object Model (DOM), and supports LINQ query expressions.

• How?

• Using classes from System.Xml.Linq namespace.

Page 29: Linq (1)

LINQ Copyright © 2015 Pratian Technologies

www.pratian.com

Unit 12 – Linq

Features of XLINQ

Create XML data from scratch by using

Query XML using XML axis.

Load XML from files or streams.

Serialize XML to files or streams.

Validate XML trees against XSD.

Manipulate the in-memory XML tree by

Remove, ReplaceWith, and SetValue.

functional construction.

using methods such as Add,

• Can transform XML trees from one shape into another

Page 30: Linq (1)

LINQ Copyright © 2015 Pratian Technologies

www.pratian.com

Unit 12 – Linq

Working with XLINQ

Function Construction using XLINQ -Code Snippet

XLINQ –Query Expressions -Code Snippet

Page 31: Linq (1)

LINQ Copyright © 2015 Pratian Technologies

www.pratian.com

Unit 12 – Linq

Reference

• Visit the following links for further details:

http://msdn.microsoft.com/en-us/library/bb397926.aspx

http://www.codeproject.com/KB/linq/

http://www.codeproject.com/Articles/19154/Understanding-LINQ-C

http://www.dotnetperls.com/join

http://www.c-sharpcorner.com/uploadfile/dhananjaycoder/linq-to-object-part-sharp1-projection/

http://www.codedigest.com/Articles/CSHARP/218_LINQ_to_Objects_in_C_.aspx

http://www.codeproject.com/Articles/26743/Using-LINQ-to-Objects-in-C

http://www.codeproject.com/Articles/286255/Using-LINQ-Queries

http://www.dotnetperls.com/linq

Page 32: Linq (1)

LINQ Copyright © 2015 Pratian Technologies

www.pratian.com

Unit 12 – Linq

Thank You