0% found this document useful (0 votes)
177 views

Language-Integrated Query (LINQ) : Content

LINQ (Language Integrated Query) provides a consistent model for querying and manipulating various data sources. It allows querying objects, XML, SQL databases and other data sources using the same basic patterns. LINQ queries can be expressed using query syntax or method syntax. Query syntax uses keywords like from, where, select, etc. while method syntax calls extension methods like Where, Select, OrderBy. LINQ queries are executed lazily, meaning the query is not run until the results are iterated over or materialized.

Uploaded by

mikkelsrensen
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
177 views

Language-Integrated Query (LINQ) : Content

LINQ (Language Integrated Query) provides a consistent model for querying and manipulating various data sources. It allows querying objects, XML, SQL databases and other data sources using the same basic patterns. LINQ queries can be expressed using query syntax or method syntax. Query syntax uses keywords like from, where, select, etc. while method syntax calls extension methods like Where, Select, OrderBy. LINQ queries are executed lazily, meaning the query is not run until the results are iterated over or materialized.

Uploaded by

mikkelsrensen
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 24

Computer Science

Language-Integrated Query
(LINQ)

Content

Introduction
LINQ to Objects

Henrk Kühll
Computer Science

Introduction

Henrk Kühll
Computer Science

Overview

• Language-Integrated Query (LINQ) provides a


consistent model for working with data across
various kinds of data sources and formats
• The same basic coding patterns are applied in
order to query and manipulate data in various
formats for which a LINQ provider is available
• A LINQ data source is any object that supports
IEnumerable, the generic IEnumerable<(Of
<(T>)>) interface, or an interface that inherits
from it, and for which a LINQ provider is
available

Henrk Kühll
Computer Science

LINQ providers

• The .NET 3.5 framework includes the following


LINQ providers
– LINQ to Objects
• .NET collections, files, strings and so on
– LINQ to SQL
• SQL server databases
– LINQ to DataSet
• ADO.NET DataSets
– LINQ to XML
• XML documents

Henrk Kühll
Computer Science

The three parts of a query operation

1. Obtain the data source


int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };
1. Create the query
var numQuery = from num in numbers
where (num % 2) == 0
select num;
1. Execute the query
foreach (int num in numQuery)
{
Console.WriteLine(num);
}

Henrk Kühll
Computer Science

The query

• The query specifies what information to


retrieve from the data source or sources
• Optionally, a query also specifies how that
information should be sorted, grouped, and
shaped before it is returned
• A query is stored in a query variable and
initialized with a query expression
• To make it easier to write queries, C# has
introduced new query syntax
• However, LINQ queries can also be expressed
using method syntax

Henrk Kühll
Computer Science

Query execution

• In LINQ the execution of the query is distinct from the


query itself
• Deferred execution
– The actual execution of the query is deferred until you iterate
over the query variable in a foreach statement
– Because the query variable itself never holds the query
results, you can execute it as often as you like
• Immediate execution
– you can force immediate execution of a query by calling the
ToList<(Of <(TSource>)>) or ToArray<(Of <(TSource>)>)
method as shown below
var numQuery = from num in numbers.ToList<int>()
where (num % 2) == 0
select num;

Henrk Kühll
Computer Science

New C# 3.0 language constructs used by


LINQ

• Query Expressions
– Queries expressions use a declarative syntax similar
to SQL or XQuery to query over IEnumerable
collections
• Implicitly Typed Variables (var)
– Instead of explicitly specifying a type when you
declare and initialize a variable, you can use the var
modifier to instruct the compiler to infer and assign
the type

Henrk Kühll
Computer Science

New C# 3.0 language constructs used by


LINQ

• Object and Collection Initializers


– Object and collection initializers make it possible to
initialize objects without explicitly calling a
constructor for the object
– Assuming a class named Customer with public Name
and Phone properties, the object initializer can be
used as in the following code

Customer cust = new Customer {Name =


“Mike”, Phone = “555-1212”};

Henrk Kühll
Computer Science

New C# 3.0 language constructs used by


LINQ

• Anonymous Types
– An anonymous type is constructed by the compiler
and the type name is only available to the compiler
– Anonymous types are initialized with a new
expression and an object initializer, as shown here

select new {name = cust.Name, phone =


cust.Phone};

Henrk Kühll
Computer Science

New C# 3.0 language constructs used by


LINQ

• Extension Methods
– An extension method is a static method that can be
associated with a type, so that it can be called as if it
were an instance method on the type
– This feature enables you to, in effect, "add" new
methods to existing types without actually modifying
them
– The standard query operators are a set of extension
methods that provide LINQ query functionality for
any type that implements IEnumerable<(Of
<(T>)>)

Henrk Kühll
Computer Science

New C# 3.0 language constructs used by


LINQ

• Auto-Implemented Properties
– Auto-implemented properties make property-
declaration more concise
public string Name {get; set;}
– When you declare a property as shown above, the
compiler converts this definition to a private field and a
default implementation
private string _name;
public string Name {
get {return this._name;}
set {this._name = value;}
}

Henrk Kühll
Computer Science

New C# 3.0 language constructs used by


LINQ

• Lambda Expressions
– A typical method consists of a return type, a method
name, a list of parameters, and a method body
– A lambda expression contains two of these elements - a
list of parameters and a method body:
(x, y) => { return x * y; }
– The left side of the lambda operator (=>) is the list of
parameters, and the right side is the method body
– The type of the parameters and the return value are
usually inferred from the context in which the lambda
expression is used (however, parameter types can be
stated explicitly)
– In LINQ programming, you will encounter lambda
expressions when you use method syntax

Henrk Kühll
Computer Science

Method syntax

• The .NET common language runtime (CLR) has no notion of


query syntax in itself
• Therefore, at compile time, query expressions are translated
to something that the CLR does understand: method calls
• These methods are called the standard query operators, and
they have names such as Where, Select, OrderBy, GroupBy,
Join, Count, Max, Min, Sum, Average, ToList etc.
• You can call them directly by using method syntax instead of
query syntax
• Examples
– var numQuery = numbers.Where(num => num % 2 == 0);
– List<Customer> Customers = …
– var custNameQuery = Customers.Where(cust =>
String.Equals(cust.City, ”London”)).Select(cust => cust.Name);

Henrk Kühll
Computer Science

LINQ to Objects

Henrk Kühll
Computer Science

Basic query operations: from

• In a LINQ query, the from clause comes first in


order to introduce the data source (customers)
and the range variable (cust):

var queryAllCustomers =
from cust in customers
select cust;

Henrk Kühll
Computer Science

Basic query operations: where

• The where clause filters the result of the query:

var queryBikeCustomers =
from cust in customers
where cust.CompanyName == "A Bike Store" || cust.
CompanyName == "Bike World"
select cust;

• You can use the familiar C# logical AND and OR


operators to apply as many filter expressions as
necessary in the where clause

Henrk Kühll
Computer Science

Basic query operations: orderby

• The orderby clause will cause the elements in the


returned sequence to be sorted according to the
default comparer for the type being sorted:

var queryFitnessCustomers =
from cust in customers
where cust.CompanyName == "Fitness
Hotel"
orderby cust.FirstName ascending
select cust;

Henrk Kühll
Computer Science

Basic query operations: group by

• The group clause enables you to group your results based


on a key that you specify:

// queryCustomersByCompany is an
// IEnumerable<IGrouping<string, Customer>>
var queryCustomersByCompany =
from cust in customers
group cust by cust.CompanyName;

• When you end a query with a group clause, your results


take the form of a list of lists. Each element in the list is an
object that has a Key member and a list of elements that
are grouped under that key.

Henrk Kühll
Computer Science

Basic query operations: group by

• When you iterate over a query that produces a sequence of


groups, you must use a nested foreach loop
• The outer loop iterates over each group, and the inner loop
iterates over each group's members

// customerGroup is an IGrouping<string, Customer>


foreach (var customerGroup in queryCustomersByCompany)
{
Console.WriteLine(customerGroup.Key);
foreach (Customer customer in customerGroup)
{
Console.WriteLine(" {0}", customer.FirstName);
}
}

Henrk Kühll
Computer Science

Basic query operations: join

• Join operations create associations between two or


more data sources:

var custJoinAddr =
from a in adresses
join c in customers
on a.CompanyName equals c.CompanyName
select new { c.FirstName, c. LastName, a.City}

• In LINQ to SQL you do not have to use join because


foreign keys are represented in the object model as
properties that hold a collection of items

Henrk Kühll
Computer Science

Basic query operations: select

• You can use the select clause to create output sequences whose
elements consist of only one or several properties of each element
in the source sequence, or output sequences whose elements
consist of the results of operations performed on the source data:
select cust.FirstName;
select new {FirstName=cust.FirstName,
LastName=cust.LastName};
select new Customer {FirstName=cust.FirstName,
LastName=cust.LastName};
select String.Format(” FirstName={0}, LastName={1},
cust. FirstName, cust. LastName”);

Henrk Kühll
Computer Science

LINQ to SQL

Henrk Kühll
Computer Science

Overview

• LINQ to SQL enables you to query or manipulate the


contents of a database
• DLINQ is built on top of ADO.NET
• Before you can use LINQ to SQL to query or manipulate
the contents of a database, you must
– Add a reference to System.Data.Linq
– Create an entity class for each table in the database that you
want to be able to access (this is referred to as the object model
or an O/R Map)
– Create a DataContext object. This object is responsible for
creating connections to the database and managing the
relationship between the entity classes and the corresponding
tables in the database

Henrk Kühll

You might also like