40
Mariano Sánchez Software Architect [email protected]

Introducción a LINQ

Embed Size (px)

Citation preview

Mariano Sánchez – Software Architect

[email protected]

var contacts =

from c in customers

where c.State == "WA"

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

var contacts =

customers

.Where(c => c.State == "WA")

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

Extension

methods

Lambda

expressions

Query

expressions

Object

initializers

Anonymous

types

Local variable

type inference

public class List<T>

{

public List<T> Where(Func<T, bool> predicate) { … }

public List<S> Select<S>(Func<T, S> selector) { … }

}

List<Customer> customers = GetCustomerList();

List<string> contacts =

customers.Where(c => c.State == "WA").Select(c => c.Name);

Operadores de

query son métodos

Que pasa con

otros tipos? Que pasa con los que

ya implementan IList?

Que pasa con

los arrays?

Componiendo

métodos

public static class Sequence

{

public static IEnumerable<T> Where<T>(IEnumerable<T> source,

Func<T, bool> predicate) { … }

public static IEnumerable<S> Select<T, S>(IEnumerable<T> source,

Func<T, S> selector) { … }

}

Customer[] customers = GetCustomerArray();

IEnumerable<string> contacts = Sequence.Select(

Sequence.Where(customers, c => c.State == "WA"),

c => c.Name);

Query como

metodos estáticos

Hmmm…

Sería bueno en

IEnumerable<T>

namespace System.Query

{

public static class Sequence

{

public static IEnumerable<T> Where<T>(this IEnumerable<T> source,

Func<T, bool> predicate) { … }

public static IEnumerable<S> Select<T, S>(this IEnumerable<T> source,

Func<T, S> selector) { … }

}

}

using System.Query;

Extension

methods

IEnumerable<string> contacts =

customers.Where(c => c.State == "WA").Select(c => c.Name);

Traigo las

extensiones

obj.Foo(x, y)

XXX.Foo(obj, x, y)

IntelliSense!

var contacts =

from c in customers

where c.State == "WA"

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

var contacts =

customers

.Where(c => c.State == "WA")

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

Extension

methods

Query

expressions

int i = 5;

string s = "Hello";

double d = 1.0;

int[] numbers = new int[] {1, 2, 3};

Dictionary<int,Order> orders = new Dictionary<int,Order>();

var i = 5;

var s = "Hello";

var d = 1.0;

var numbers = new int[] {1, 2, 3};

var orders = new Dictionary<int,Order>();

var contacts =

from c in customers

where c.State == "WA"

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

var contacts =

customers

.Where(c => c.State == "WA")

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

Local variable

type inference

public class Point

{

private int x, y;

public int X { get { return x; } set { x = value; } }

public int Y { get { return y; } set { y = value; } }

}

Point a = new Point { X = 0, Y = 1 };

Point a = new Point();

a.X = 0;

a.Y = 1;

Asignar campos

o propiedades

List<int> powers = new List<int>{ 1, 10, 100, 1000, 10000 };

Debe implementar

ICollection<T>

List<int> powers = new List<int>();

powers.Add(1);

powers.Add(10);

powers.Add(100);

powers.Add(1000);

powers.Add(10000);

var contacts =

from c in customers

where c.State == "WA"

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

var contacts =

customers

.Where(c => c.State == "WA")

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

Object

initializers

public class Customer

{

public string Name;

public Address Address;

public string Phone;

public List<Order> Orders;

}

public class Contact

{

public string Name;

public string Phone;

}

Customer c = GetCustomer(…);

Contact x = new Contact { Name = c.Name, Phone = c.Phone };

Customer c = GetCustomer(…);

var x = new { c.Name, c.Phone };

Customer c = GetCustomer(…);

var x = new { Name = c.Name, Phone = c.Phone };

var contacts =

from c in customers

where c.State == "WA"

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

var contacts =

customers.

.Where(c => c.State == "WA“)

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

foreach (var c in contacts) {

Console.WriteLine(c.Name);

Console.WriteLine(c.Phone);

}

var contacts =

from c in customers

where c.State == "WA"

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

var contacts =

customers

.Where(c => c.State == "WA")

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

Anonymous

types

Standard

Query

Operators

Objects

Linq to Sql

(ADO.NET)

XLinq

(System.Xml)

<book>

<title/>

<author/>

<year/>

<price/>

</book>

XML

.NET Language Integrated Query

C# 3.0 VB 9.0 Others…

SQL

var contacts =

from c in customers

where c.State == "WA"

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

class Contact { … };

List<Contact> contacts = new List<Contacts>();

foreach(Customer c in customers)

{

if(c.State == “WA”)

{

Contact ct = new Contact();

ct.Name = c.Name;

ct.Phone = c.Phone;

contacts.Add(ct);

}

}

try

catch

finally

try

catch

Restriction Where, Contains

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

Conversion ToArray, ToList, ToDictionary

Casting OfType<T>

LINQ to SQL

demo

• Mejorar la forma de procesar Xml Creando nuevas instancias

Modificando instancias existentes

Consultando instancias en memoria

Combinando consultas entre Xml, Objetos y Datos

< >

< >

< > / >

< type= home > </ >

< type= work > </ >

< >

< > </ >

< > </ >

< > </ >

< > </ >

</ >

< > </ >

</ >

< >

< > </ >

< type= mobile > </ >

< >

< > </ >

< > </ >

< > </ >

< > </ >

</ >

< > </ >

</ >

</ >

XmlDocument new XmlDocument

XmlElement "name"

“Diego Gonzalez"

XmlElement "phone"

"type" "home"

"206-555-0144"

XmlElement "phone"

"type" "work"

"425-555-0145"

XmlElement

"street1"

"123 Main St"

XmlElement "city"

"Mercer Island"

XmlElement "state"

"WA"

XmlElement

"postal"

"68042"

XmlElement

"address"

XmlElement

"contact"

XmlElement

"contacts"

XElement

new XElement "contacts"

new XElement "contact"

new XElement "name" "Patrick Hines"

new XElement "phone" "206-555-0144"

new XAttribute "type" "home"

new XElement "phone" "425-555-0145"

new XAttribute "type" "work"

new XElement "address"new XElement "street1" "123 Main St"new XElement "city" "Mercer Island"new XElement "state" "WA"

new XElement "postal" "68042"

var result = new XElement "contacts"

from in "contact"

select new

new XComment "contact"

new XElement "name" string "name"

"phone"

new XElement "address" "address"

• Basado en un modelo conceptual Entity y EntitySet

• Se mapea con el modelo relacional de la base de datos permitiendo abarcar mas escenarios.

Muchas Gracias

Mariano Sánchez – Software Architect

[email protected]