SlideShare a Scribd company logo
Mariano Sánchez – Software Architect
marianos@lagash.com
Local variable
type inference

var contacts =
from c in customers
where c.State == "WA"
select new { c.Name, c.Phone };

Query
expressions

Lambda
expressions

var contacts =
customers
.Where(c => c.State == "WA")
.Select(c => new { c.Name, c.Phone });
Extension
methods

Anonymous
types

Object
initializers
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);

Que pasa con
otros tipos?

Que pasa con los que
ya implementan IList?
Que pasa con
los arrays?

Operadores de
query son métodos

Componiendo
métodos
Query como
metodos estáticos

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) { … }
…
}

Hmmm…
Customer[] customers = GetCustomerArray();
IEnumerable<string> contacts = Sequence.Select(
Sequence.Where(customers, c => c.State == "WA"),
c => c.Name);

Sería bueno en
IEnumerable<T>
namespace System.Query
Extension
{
methods
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) { … }
…
}

Traigo las
extensiones

}
using System.Query;

IEnumerable<string> contacts =
customers.Where(c => c.State == "WA").Select(c => c.Name);

IntelliSense!

obj.Foo(x, y)

XXX.Foo(obj, x, y)
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>();
Local variable
type inference

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 });
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
Debe implementar
ICollection<T>
List<int> powers = new List<int>{ 1, 10, 100, 1000, 10000 };
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 { Name = c.Name, Phone = c.Phone };

Customer c = GetCustomer(…);
var x = new { c.Name, 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
C# 3.0

VB 9.0

Others…

.NET Language Integrated Query

Standard
Query
Operators

Linq to Sql
(ADO.NET)

XLinq
(System.Xml)

<book>
<title/>
<author/>
<year/>
<price/>
</book>

Objects

SQL

XML
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);
}
}
var contacts =
from c in customers
where c.State == "WA"
select new { c.Name, c.Phone };
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>
demo

LINQ to SQL
• 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
XmlElement

new XmlDocument
"name"
“Diego Gonzalez"

XmlElement

"phone"
"type" "home"
"206-555-0144"

XmlElement

XmlElement
"contact"

"phone"
"type" "work"
"425-555-0145"

XmlElement
"street1"
"123 Main St"

XmlElement

XmlElement
"contacts"

"city"
"Mercer Island"

XmlElement

"state"
"WA"

XmlElement
"postal"
"68042"
XmlElement
"address"
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
marianos@lagash.com

More Related Content

What's hot

The Ring programming language version 1.3 book - Part 24 of 88
The Ring programming language version 1.3 book - Part 24 of 88The Ring programming language version 1.3 book - Part 24 of 88
The Ring programming language version 1.3 book - Part 24 of 88Mahmoud Samir Fayed
 
Type script by Howard
Type script by HowardType script by Howard
Type script by HowardLearningTech
 
Informatics Practices/ Information Practices Project (IP Project Class 12)
Informatics Practices/ Information Practices Project (IP Project Class 12)Informatics Practices/ Information Practices Project (IP Project Class 12)
Informatics Practices/ Information Practices Project (IP Project Class 12)KushShah65
 
TypeScript by Howard
TypeScript by HowardTypeScript by Howard
TypeScript by HowardLearningTech
 
Data oriented design
Data oriented designData oriented design
Data oriented designMax Klyga
 
FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2rohassanie
 

What's hot (13)

C++ Template
C++ TemplateC++ Template
C++ Template
 
The Ring programming language version 1.3 book - Part 24 of 88
The Ring programming language version 1.3 book - Part 24 of 88The Ring programming language version 1.3 book - Part 24 of 88
The Ring programming language version 1.3 book - Part 24 of 88
 
Type script by Howard
Type script by HowardType script by Howard
Type script by Howard
 
Informatics Practices/ Information Practices Project (IP Project Class 12)
Informatics Practices/ Information Practices Project (IP Project Class 12)Informatics Practices/ Information Practices Project (IP Project Class 12)
Informatics Practices/ Information Practices Project (IP Project Class 12)
 
TypeScript by Howard
TypeScript by HowardTypeScript by Howard
TypeScript by Howard
 
Data oriented design
Data oriented designData oriented design
Data oriented design
 
FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2
 
Template C++ OOP
Template C++ OOPTemplate C++ OOP
Template C++ OOP
 
Templates
TemplatesTemplates
Templates
 
Container adapters
Container adaptersContainer adapters
Container adapters
 
Unit 4 (1)
Unit 4 (1)Unit 4 (1)
Unit 4 (1)
 
Final ds record
Final ds recordFinal ds record
Final ds record
 
Templates
TemplatesTemplates
Templates
 

Similar to Introducción a LINQ

Linq 090701233237 Phpapp01
Linq 090701233237 Phpapp01Linq 090701233237 Phpapp01
Linq 090701233237 Phpapp01google
 
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05CHOOSE
 
Share pointtechies linqtosp-andsbs
Share pointtechies linqtosp-andsbsShare pointtechies linqtosp-andsbs
Share pointtechies linqtosp-andsbsShakir Majeed Khan
 
Linq Sanjay Vyas
Linq   Sanjay VyasLinq   Sanjay Vyas
Linq Sanjay Vyasrsnarayanan
 
Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#Vagif Abilov
 
C# 3.0 Language Innovations
C# 3.0 Language InnovationsC# 3.0 Language Innovations
C# 3.0 Language InnovationsShahriar Hyder
 
help me Java projectI put problem and my own code in the linkmy .pdf
help me Java projectI put problem and my own code in the linkmy .pdfhelp me Java projectI put problem and my own code in the linkmy .pdf
help me Java projectI put problem and my own code in the linkmy .pdfarihantmum
 
Advanced dot net
Advanced dot netAdvanced dot net
Advanced dot netssa2010
 
C# Starter L04-Collections
C# Starter L04-CollectionsC# Starter L04-Collections
C# Starter L04-CollectionsMohammad Shaker
 
Sqlforetltesting 130712042826-phpapp01
Sqlforetltesting 130712042826-phpapp01Sqlforetltesting 130712042826-phpapp01
Sqlforetltesting 130712042826-phpapp01Gyanendra Kumar
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012Sandeep Joshi
 

Similar to Introducción a LINQ (20)

Linq 090701233237 Phpapp01
Linq 090701233237 Phpapp01Linq 090701233237 Phpapp01
Linq 090701233237 Phpapp01
 
Introduction to Linq
Introduction to LinqIntroduction to Linq
Introduction to Linq
 
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
 
Share pointtechies linqtosp-andsbs
Share pointtechies linqtosp-andsbsShare pointtechies linqtosp-andsbs
Share pointtechies linqtosp-andsbs
 
Linq Sanjay Vyas
Linq   Sanjay VyasLinq   Sanjay Vyas
Linq Sanjay Vyas
 
Greg Demo Slides
Greg Demo SlidesGreg Demo Slides
Greg Demo Slides
 
Understanding linq
Understanding linqUnderstanding linq
Understanding linq
 
Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#
 
PostThis
PostThisPostThis
PostThis
 
Linq intro
Linq introLinq intro
Linq intro
 
C sharp 8
C sharp 8C sharp 8
C sharp 8
 
C# 3.0 Language Innovations
C# 3.0 Language InnovationsC# 3.0 Language Innovations
C# 3.0 Language Innovations
 
help me Java projectI put problem and my own code in the linkmy .pdf
help me Java projectI put problem and my own code in the linkmy .pdfhelp me Java projectI put problem and my own code in the linkmy .pdf
help me Java projectI put problem and my own code in the linkmy .pdf
 
Dat402
Dat402Dat402
Dat402
 
Advanced dot net
Advanced dot netAdvanced dot net
Advanced dot net
 
Lesson11
Lesson11Lesson11
Lesson11
 
C# Starter L04-Collections
C# Starter L04-CollectionsC# Starter L04-Collections
C# Starter L04-Collections
 
Sqlforetltesting 130712042826-phpapp01
Sqlforetltesting 130712042826-phpapp01Sqlforetltesting 130712042826-phpapp01
Sqlforetltesting 130712042826-phpapp01
 
SQL for ETL Testing
SQL for ETL TestingSQL for ETL Testing
SQL for ETL Testing
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012
 

More from Mariano Sánchez

More from Mariano Sánchez (18)

.NET Core
.NET Core.NET Core
.NET Core
 
ASP.NET Core 1.0
ASP.NET Core 1.0ASP.NET Core 1.0
ASP.NET Core 1.0
 
Introducción a SignalR
Introducción a SignalRIntroducción a SignalR
Introducción a SignalR
 
Visual Studio LightSwitch
Visual Studio LightSwitchVisual Studio LightSwitch
Visual Studio LightSwitch
 
HTML5 + Asp.NET
HTML5 + Asp.NETHTML5 + Asp.NET
HTML5 + Asp.NET
 
Hey Cortana!
Hey Cortana!Hey Cortana!
Hey Cortana!
 
Developing Universal Apps for Windows
Developing Universal Apps for WindowsDeveloping Universal Apps for Windows
Developing Universal Apps for Windows
 
Introducing the Windows Phone 8.1 App Development Platform
Introducing the Windows Phone 8.1 App Development PlatformIntroducing the Windows Phone 8.1 App Development Platform
Introducing the Windows Phone 8.1 App Development Platform
 
Visual Studio Online
Visual Studio OnlineVisual Studio Online
Visual Studio Online
 
Patrones Grasp
Patrones GraspPatrones Grasp
Patrones Grasp
 
Patrones de Diseño
Patrones de DiseñoPatrones de Diseño
Patrones de Diseño
 
Introducción a DDD
Introducción a DDDIntroducción a DDD
Introducción a DDD
 
Conociendo TypeScript
Conociendo TypeScriptConociendo TypeScript
Conociendo TypeScript
 
C# 6 - Que hay de nuevo?
C# 6 - Que hay de nuevo?C# 6 - Que hay de nuevo?
C# 6 - Que hay de nuevo?
 
Universal Windows Platform Programando para todos y todas
Universal Windows PlatformProgramando para todos y todasUniversal Windows PlatformProgramando para todos y todas
Universal Windows Platform Programando para todos y todas
 
Code Smells
Code SmellsCode Smells
Code Smells
 
Refactoring - Mejorando el diseño del código existente
Refactoring - Mejorando el diseño del código existenteRefactoring - Mejorando el diseño del código existente
Refactoring - Mejorando el diseño del código existente
 
Patrones de Diseño
Patrones de DiseñoPatrones de Diseño
Patrones de Diseño
 

Recently uploaded

Workforce Efficiency with Employee Time Tracking Software.pdf
Workforce Efficiency with Employee Time Tracking Software.pdfWorkforce Efficiency with Employee Time Tracking Software.pdf
Workforce Efficiency with Employee Time Tracking Software.pdfDeskTrack
 
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdfA Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdfkalichargn70th171
 
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)Gáspár Nagy
 
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdf
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdfImplementing KPIs and Right Metrics for Agile Delivery Teams.pdf
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdfVictor Lopez
 
Studiovity film pre-production and screenwriting software
Studiovity film pre-production and screenwriting softwareStudiovity film pre-production and screenwriting software
Studiovity film pre-production and screenwriting softwareinfo611746
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...Alluxio, Inc.
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesKrzysztofKkol1
 
KLARNA - Language Models and Knowledge Graphs: A Systems Approach
KLARNA -  Language Models and Knowledge Graphs: A Systems ApproachKLARNA -  Language Models and Knowledge Graphs: A Systems Approach
KLARNA - Language Models and Knowledge Graphs: A Systems ApproachNeo4j
 
Breaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdfBreaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdfMeon Technology
 
JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)Max Lee
 
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with StrimziStrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzisteffenkarlsson2
 
INGKA DIGITAL: Linked Metadata by Design
INGKA DIGITAL: Linked Metadata by DesignINGKA DIGITAL: Linked Metadata by Design
INGKA DIGITAL: Linked Metadata by DesignNeo4j
 
CompTIA Security+ (Study Notes) for cs.pdf
CompTIA Security+ (Study Notes) for cs.pdfCompTIA Security+ (Study Notes) for cs.pdf
CompTIA Security+ (Study Notes) for cs.pdfFurqanuddin10
 
How to install and activate eGrabber JobGrabber
How to install and activate eGrabber JobGrabberHow to install and activate eGrabber JobGrabber
How to install and activate eGrabber JobGrabbereGrabber
 
OpenChain @ LF Japan Executive Briefing - May 2024
OpenChain @ LF Japan Executive Briefing - May 2024OpenChain @ LF Japan Executive Briefing - May 2024
OpenChain @ LF Japan Executive Briefing - May 2024Shane Coughlan
 
10 Essential Software Testing Tools You Need to Know About.pdf
10 Essential Software Testing Tools You Need to Know About.pdf10 Essential Software Testing Tools You Need to Know About.pdf
10 Essential Software Testing Tools You Need to Know About.pdfkalichargn70th171
 
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product UpdatesGraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product UpdatesNeo4j
 
iGaming Platform & Lottery Solutions by Skilrock
iGaming Platform & Lottery Solutions by SkilrockiGaming Platform & Lottery Solutions by Skilrock
iGaming Platform & Lottery Solutions by SkilrockSkilrock Technologies
 

Recently uploaded (20)

Workforce Efficiency with Employee Time Tracking Software.pdf
Workforce Efficiency with Employee Time Tracking Software.pdfWorkforce Efficiency with Employee Time Tracking Software.pdf
Workforce Efficiency with Employee Time Tracking Software.pdf
 
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdfA Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
 
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
 
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdf
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdfImplementing KPIs and Right Metrics for Agile Delivery Teams.pdf
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdf
 
Studiovity film pre-production and screenwriting software
Studiovity film pre-production and screenwriting softwareStudiovity film pre-production and screenwriting software
Studiovity film pre-production and screenwriting software
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
 
KLARNA - Language Models and Knowledge Graphs: A Systems Approach
KLARNA -  Language Models and Knowledge Graphs: A Systems ApproachKLARNA -  Language Models and Knowledge Graphs: A Systems Approach
KLARNA - Language Models and Knowledge Graphs: A Systems Approach
 
Breaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdfBreaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdf
 
JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)
 
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with StrimziStrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi
 
INGKA DIGITAL: Linked Metadata by Design
INGKA DIGITAL: Linked Metadata by DesignINGKA DIGITAL: Linked Metadata by Design
INGKA DIGITAL: Linked Metadata by Design
 
CompTIA Security+ (Study Notes) for cs.pdf
CompTIA Security+ (Study Notes) for cs.pdfCompTIA Security+ (Study Notes) for cs.pdf
CompTIA Security+ (Study Notes) for cs.pdf
 
How to install and activate eGrabber JobGrabber
How to install and activate eGrabber JobGrabberHow to install and activate eGrabber JobGrabber
How to install and activate eGrabber JobGrabber
 
5 Reasons Driving Warehouse Management Systems Demand
5 Reasons Driving Warehouse Management Systems Demand5 Reasons Driving Warehouse Management Systems Demand
5 Reasons Driving Warehouse Management Systems Demand
 
Top Mobile App Development Companies 2024
Top Mobile App Development Companies 2024Top Mobile App Development Companies 2024
Top Mobile App Development Companies 2024
 
OpenChain @ LF Japan Executive Briefing - May 2024
OpenChain @ LF Japan Executive Briefing - May 2024OpenChain @ LF Japan Executive Briefing - May 2024
OpenChain @ LF Japan Executive Briefing - May 2024
 
10 Essential Software Testing Tools You Need to Know About.pdf
10 Essential Software Testing Tools You Need to Know About.pdf10 Essential Software Testing Tools You Need to Know About.pdf
10 Essential Software Testing Tools You Need to Know About.pdf
 
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product UpdatesGraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
 
iGaming Platform & Lottery Solutions by Skilrock
iGaming Platform & Lottery Solutions by SkilrockiGaming Platform & Lottery Solutions by Skilrock
iGaming Platform & Lottery Solutions by Skilrock
 

Introducción a LINQ

  • 1. Mariano Sánchez – Software Architect marianos@lagash.com
  • 2.
  • 3.
  • 4.
  • 5.
  • 6. Local variable type inference var contacts = from c in customers where c.State == "WA" select new { c.Name, c.Phone }; Query expressions Lambda expressions var contacts = customers .Where(c => c.State == "WA") .Select(c => new { c.Name, c.Phone }); Extension methods Anonymous types Object initializers
  • 7. 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); Que pasa con otros tipos? Que pasa con los que ya implementan IList? Que pasa con los arrays? Operadores de query son métodos Componiendo métodos
  • 8. Query como metodos estáticos 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) { … } … } Hmmm… Customer[] customers = GetCustomerArray(); IEnumerable<string> contacts = Sequence.Select( Sequence.Where(customers, c => c.State == "WA"), c => c.Name); Sería bueno en IEnumerable<T>
  • 9. namespace System.Query Extension { methods 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) { … } … } Traigo las extensiones } using System.Query; IEnumerable<string> contacts = customers.Where(c => c.State == "WA").Select(c => c.Name); IntelliSense! obj.Foo(x, y)  XXX.Foo(obj, x, y)
  • 10. 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
  • 11. 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>();
  • 12. Local variable type inference 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 });
  • 13. 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
  • 14. Debe implementar ICollection<T> List<int> powers = new List<int>{ 1, 10, 100, 1000, 10000 }; List<int> powers = new List<int>(); powers.Add(1); powers.Add(10); powers.Add(100); powers.Add(1000); powers.Add(10000);
  • 15. 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
  • 16. 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 { Name = c.Name, Phone = c.Phone }; Customer c = GetCustomer(…); var x = new { c.Name, c.Phone };
  • 17. 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); }
  • 18. 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
  • 19. C# 3.0 VB 9.0 Others… .NET Language Integrated Query Standard Query Operators Linq to Sql (ADO.NET) XLinq (System.Xml) <book> <title/> <author/> <year/> <price/> </book> Objects SQL XML
  • 20. 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); } } var contacts = from c in customers where c.State == "WA" select new { c.Name, c.Phone };
  • 21.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28. 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>
  • 30.
  • 31. • Mejorar la forma de procesar Xml     Creando nuevas instancias Modificando instancias existentes Consultando instancias en memoria Combinando consultas entre Xml, Objetos y Datos
  • 32. < > < </ < </ </ > > < < < < </ < > > < < < </ < > > / type= home > type= work > > < > < > < > </ < > > > </ > > </ </ </ </ > > > > > </ > > </ type= mobile > > < > < > < > </ > < > </ > > </ > > </ </ </ > > > >
  • 33. XmlDocument XmlElement new XmlDocument "name" “Diego Gonzalez" XmlElement "phone" "type" "home" "206-555-0144" XmlElement XmlElement "contact" "phone" "type" "work" "425-555-0145" XmlElement "street1" "123 Main St" XmlElement XmlElement "contacts" "city" "Mercer Island" XmlElement "state" "WA" XmlElement "postal" "68042" XmlElement "address"
  • 34. 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"
  • 35. var result = new XElement "contacts" from in "contact" select new new XComment "contact" new XElement "name" string "name" "phone" new XElement "address" "address"
  • 36.
  • 37. • Basado en un modelo conceptual  Entity y EntitySet • Se mapea con el modelo relacional de la base de datos permitiendo abarcar mas escenarios.
  • 38.
  • 39.
  • 40. Muchas Gracias Mariano Sánchez – Software Architect marianos@lagash.com