SlideShare ist ein Scribd-Unternehmen logo
1 von 30
Downloaden Sie, um offline zu lesen
Language INtegrated Query
(LINQ)
Eng. Mahmoud Ouf
Lecture 2
mmouf@2017
Introduction To LINQ
• Problems in accessing Data from Different DataSource:
We Can’t programmatically interact with a database at the native language
level
Trouble caused by conflict data types utilized versus the native language of
the program
mmouf@2017
LINQ
• Microsoft’s technology to provide a language-level support mechanism for
querying data of all types.
in-memory arrays and collections,
databases,
XML documents, and more.
• The returned Set of objects is called “sequence”
• Most sequence are of type IEnumerable<T>
• LINQ is not for query as in its name, We can better think of it as Data
Integration Engine (DIE)
mmouf@2017
LINQ Definition
• LINQ is a uniform programming model for any kind of data.
• LINQ enables you to query and manipulate data with a consistent model
that is independent from data sources.
• LINQ is just another tool for embedding SQL queries into code.
• LINQ is yet another data abstraction layer.
LINQ is all the previous and more
• LINQ is a methodology that simplifies and unifies the implementation of
any kind of data access.
• LINQ does not force you to use a specific architecture; it facilitates the
implementation of several existing architectures for accessing data.
mmouf@2017
LINQ
mmouf@2017
LINQ Query Expression
• Query expressions are written in a declarative query syntax introduced in
C# 3.0
• Use the same basic query expression patterns to query and transform data
in SQL databases, ADO.NET Datasets, XML documents and streams, and
.NET collections
• All LINQ query operations consist of three distinct actions:
1. Obtain the data source.
2. Create the query.
3. Execute the query.
mmouf@2017
LINQ Query Expression
• LINQ use deffered execution:
• A query is not executed until you iterate over the query variable in a
foreach statement, this is named deffered execution.
• The benefit of this approach is that you are able to apply the same LINQ
query multiple times to the same container, and rest assured you are
obtaining the latest and greatest results
mmouf@2017
LINQ Query Expression
• The general form of the query expression is:
• from id in source
• {Where condition |
• Orderby ordering, ordering, ... [Ascending | Descending] }
• Select expr | ;
mmouf@2017
LINQ Query Expression
class LINQQueryExpressions
{
static void Main()
{
// Specify the data source.
int[] scores = new int[] { 97, 92, 81, 60 };
// Define the query expression.
IEnumerable<int> scoreQuery =
from score in scores
where score > 80
select score;
// Execute the query.
foreach (int i in scoreQuery)
{
Console.Write(i + " ");
} mmouf@2017
LINQ Query Expression
//Make a change
Scores[0] = 50;
Console.WriteLine();
// Re-Execute the query.
foreach (int i in scoreQuery)
{
Console.Write(i + " ");
}
}
}
// Output: 97 92 81
// 92 81
mmouf@2017
LINQ and Implicitly Typed Local Variable
static void QueryOverInts()
{
int[] numbers = {10, 20, 30, 40, 1, 2, 3, 8};
// Use implicit typing here...
var subset = from i in numbers where i < 10 select i;
// ...and here.
foreach (var i in subset)
Console.WriteLine("Item: {0} ", i);
}
mmouf@2017
LINQ and Extension method
LINQ provides an API known as standard query Methods to support the
kinds of operations we’re accustomed to in SQL.
All standard query methods, are actually methods of the
System.Linq.Enumerable static class.
The Enumerable type provides a set of methods that do not have a direct C#
query operator shorthand notation, but are instead exposed as extension
methods.
These generic methods can be called to transform a result set in various
manners (Reverse<>(), ToArray<>(), ToList<>(), etc.).
Some are used to extract singletons from a result set, others perform various
set operations (Distinct<>(), Union<>(), Intersect<>(), etc.), and still others
aggregate results (Count<>(), Sum<>(), Min<>(), Max<>()
mmouf@2017
LINQ and Extension method
static void GetCount()
{
string[] currentVideoGames = {"Morrowind", "BioShock", "Half Life 2: Episode
1", "The Darkness", "Daxter", "System Shock 2"};
// Get count from the query.
int numb = (from g in currentVideoGames
where g.Length > 6
orderby g
select g).Count<string>();
// numb is the value 5.
Console.WriteLine("{0} items honor the LINQ query.", numb);
}
mmouf@2017
Returning the Result of a LINQ Query
It is possible to define a field within a class (or structure) whose value is the
result of a LINQ query.
To do so, however, you cannot make use of implicit typing (as the var
keyword cannot be used for fields), and the target of the LINQ query cannot
be instance-level data; therefore, it must be static.
class LINQBasedFieldsAreClunky
{
private static string[] currentVideoGames = {"Morrowind",
"Uncharted 2", "Fallout 3", "Daxter", "System Shock 2"};
// Can’t use implicit typing here! Must know type of subset!
private IEnumerable<string> subset = from g in currentVideoGames
where g.Contains(" ") orderby g select g;
mmouf@2017
Returning the Result of a LINQ Query
public void PrintGames()
{
foreach (var item in subset)
{
Console.WriteLine(item);
}
}
}
mmouf@2017
Returning the Result of a LINQ Query
Implicitly typed variables cannot be used to define parameters, return values,
or fields of a class or structure.
So, how you could return a query result to an external caller?. The answer is,
it depends. If you have a result set consisting of strongly typed data, such as
an array of strings or a List<T> of Cars, you could abandon the use of the
var keyword and use a proper IEnumerable<T> or IEnumerable type
class Program
{
static void Main(string[] args)
{
Console.WriteLine("***** LINQ Return Values *****n");
IEnumerable<string> subset = GetStringSubset();
foreach (string item in subset)
{
mmouf@2017
Returning the Result of a LINQ Query
Console.WriteLine(item);
}
Console.ReadLine();
}
static IEnumerable<string> GetStringSubset()
{
string[] colors = {"Light Red", "Green","Yellow", "Dark Red", "Red",
"Purple"};
// Note subset is an IEnumerable<string>-compatible object.
IEnumerable<string> theRedColors = from c in colors
where c.Contains("Red") select c;
return theRedColors;
}
}
mmouf@2017
Extension Methods of Enumerable class
The Enumerable class supports a set of extension methods that allows you to
use two (or more) LINQ queries as the basis to find unions, differences,
concatenations, and intersections of data.
•Except Method
Extension method, which will return a LINQ result set that contains the differences
between two containers, which in this case, is the value Yugo:
static void DisplayDiff()
{
List<string> myCars = new List<String> {"Yugo", "Aztec", "BMW"};
List<string> yourCars = new List<String>{"BMW", "Saab", "Aztec" };
var carDiff =(from c in myCars select c).Except(from c2 in yourCars select c2);
Console.WriteLine("Here is what you don’t have, but I do:");
foreach (string s in carDiff)
Console.WriteLine(s); // Prints Yugo.
} mmouf@2017
Extension Methods of Enumerable class
•Intersect Method
Extension method will return a result set that contains the common data items in a set of
containers. For example, the following method returns the sequence Aztec and BMW:
static void DisplayIntersection()
{
List<string> myCars = new List<String> { "Yugo", "Aztec", "BMW" };
List<string> yourCars = new List<String> { "BMW", "Saab", "Aztec" };
// Get the common members.
var carIntersect = (from c in myCars select c).Intersect(from c2 in yourCars select
c2);
Console.WriteLine("Here is what we have in common:");
foreach (string s in carIntersect)
Console.WriteLine(s); // Prints Aztec and BMW.
}
mmouf@2017
Extension Methods of Enumerable class
•Union Method
Extension method returns a result set that includes all members of a batch of LINQ
queries. Like any proper union, you will not find repeating values if a common member
appears more than once. Therefore, the following method will print out the values Yugo,
Aztec, BMW, and Saab:
static void DisplayUnion()
{
List<string> myCars = new List<String> { "Yugo", "Aztec", "BMW" };
List<string> yourCars = new List<String> { "BMW", "Saab", "Aztec" };
// Get the union of these containers.
var carUnion = (from c in myCars select c).Union(from c2 in yourCars select c2);
Console.WriteLine("Here is everything:");
foreach (string s in carUnion)
Console.WriteLine(s); // Prints all common members.
}
mmouf@2017
Extension Methods of Enumerable class
•Concat Method
Extension method returns a result set that is a direct concatenation of LINQ result sets.
For example, the following method prints out the results Yugo, Aztec, BMW, BMW,
Saab, and Aztec:
static void DisplayConcat()
{
List<string> myCars = new List<String> { "Yugo", "Aztec", "BMW" };
List<string> yourCars = new List<String> { "BMW", "Saab", "Aztec" };
var carConcat = (from c in myCars select c).Concat(from c2 in yourCars select
c2);
// Prints: Yugo Aztec BMW BMW Saab Aztec.
foreach (string s in carConcat)
Console.WriteLine(s);
}
mmouf@2017
Extension Methods of Enumerable class
•Distinct Method
When you call the Concat() extension method, you could very well end up with
redundant entries in the fetched result, which could be exactly what you want in some
cases. However, in other cases, you might want to remove duplicate entries in your data.
To do so, simply call the Distinct() extension method
static void DisplayConcatNoDups()
{
List<string> myCars = new List<String> { "Yugo", "Aztec", "BMW" };
List<string> yourCars = new List<String> { "BMW", "Saab", "Aztec" };
var carConcat = (from c in myCars select c).Distinct(from c2 in yourCars select c2);
// Prints: Yugo Aztec BMW Saab.
foreach (string s in carConcat.Distinct())
Console.WriteLine(s);
}
mmouf@2017
The Internal Representation of LINQ Query Statements
At this point, we have been introduced to the process of building query
expressions using various C# query operators (such as from, in, where,
orderby, and select).
Also, we discovered that some functionality of the LINQ to Objects API can
be accessed only when calling extension methods of the Enumerable class.
The truth of the matter, however, is that when compiled, the C# compiler
actually translates all C# LINQ operators into calls on methods of the
Enumerable class.
A great many of the methods of Enumerable have been prototyped to take
delegates as arguments.
mmouf@2017
Building Query Expressions Using the Enumerable
Type and Lambda Expressions
Consider the following QueryStringsWithEnumerableAndLambdas()
method, which is processing the local string array now making direct use of
the Enumerable extension methods.
static void QueryStringsWithEnumerableAndLambdas()
{
string[] currentVideoGames = {"Morrowind", "Uncharted 2", "Fallout 3",
"Daxter", "System Shock 2"};
// Build a query expression using extension methods
// granted to the Array via the Enumerable type.
var subset = currentVideoGames.Where(game => game.Contains("
")).OrderBy(game => game).Select(game => game);
mmouf@2017
Building Query Expressions Using the Enumerable
Type and Lambda Expressions
// Print out the results.
foreach (var game in subset)
Console.WriteLine("Item: {0}", game);
Console.WriteLine();
}
mmouf@2017
LINQ to Object
•Linq and Array
static void QueryOverStrings()
{
// Assume we have an array of strings. (Step 1)
string[] currentVideoGames = {"Morrowind", "BioShock", "Half Life 2: Episode 1", "The
Darkness", "Daxter", "System Shock 2"};
// Build a query expression to represent the items in the array
// that have more than 6 letters. (Step 2)
IEnumerable<string> subset = from g in currentVideoGames
where g.Length > 6 orderby g select g;
// Print out the results. (Step 3)
foreach (string s in subset)
Console.WriteLine("Item: {0}", s);
}
mmouf@2017
LINQ to Object
•Linq and Generic Collection
class Car
{
public string PetName = string.Empty;
public string Color = string.Empty;
public int Speed;
public string Make = string.Empty;
}
static void Main(string[] args)
{
// Make a List<> of Car objects using object init syntax. (Step 1)
List<Car> myCars = new List<Car>() {
new Car{ PetName = "Henry", Color = "Silver", Speed = 100, Make = "BMW"},
new Car{ PetName = "Daisy", Color = "Tan", Speed = 90, Make = "BMW"},
new Car{ PetName = "Mary", Color = "Black", Speed = 55, Make = "VW"},
new Car{ PetName = "Clunker", Color = "Rust", Speed = 5, Make = "Yugo"},
new Car{ PetName = "Melvin", Color = "White", Speed = 43, Make = "Ford"} };
mmouf@2017
LINQ to Object
•Linq and Generic Collection
// Create a query expression . (Step 2)
var fastCars = from c in myCars where
c.Speed > 90 && c.Make == "BMW" select c;
//Execute the Query. (Step 3)
foreach (var car in fastCars)
{
Console.WriteLine("{0} is going too fast!", car.PetName);
}
}
mmouf@2017
LINQ to Object
•Linq and Non-Generic Collection
LINQ are designed to work with any type implementing IEnumerable<T>, The Non-Generic collection
doesn’t implement IEnumerable<T>. So, need to transform it to a Generic Collection First
class Car
{
public string PetName = string.Empty;
public string Color = string.Empty;
public int Speed;
public string Make = string.Empty;
}
static void Main(string[] args)
{
// Make a List<> of Car objects using object init syntax. (Step 1)
ArrayList<Car> myCars = new ArrayList<Car>() {
new Car{ PetName = "Henry", Color = "Silver", Speed = 100, Make = "BMW"},
new Car{ PetName = "Daisy", Color = "Tan", Speed = 90, Make = "BMW"},
mmouf@2017
LINQ to Object
•Linq and Non-Generic Collection
new Car{ PetName = "Mary", Color = "Black", Speed = 55, Make = "VW"},
new Car{ PetName = "Clunker", Color = "Rust", Speed = 5, Make = "Yugo"},
new Car{ PetName = "Melvin", Color = "White", Speed = 43, Make = "Ford"} };
// Transform ArrayList into an IEnumerable<T>-compatible type.
IEnumerable<Car> myCarsEnum = myCars.OfType<Car>();
// Create a query expression . (Step 2)
var fastCars = from c in myCarsEnum where
c.Speed > 90 && c.Make == "BMW" select c;
//Execute the query. (Step 3)
foreach (var car in fastCars)
Console.WriteLine("{0} is going too fast!", car.PetName);
}
mmouf@2017

Weitere ähnliche Inhalte

Was ist angesagt?

Language Integrated Query By Nyros Developer
Language Integrated Query By Nyros DeveloperLanguage Integrated Query By Nyros Developer
Language Integrated Query By Nyros DeveloperNyros Technologies
 
Language Integrated Query - LINQ
Language Integrated Query - LINQLanguage Integrated Query - LINQ
Language Integrated Query - LINQDoncho Minkov
 
Module 3: Introduction to LINQ (PowerPoint Slides)
Module 3: Introduction to LINQ (PowerPoint Slides)Module 3: Introduction to LINQ (PowerPoint Slides)
Module 3: Introduction to LINQ (PowerPoint Slides)Mohamed Saleh
 
Differences between method overloading and method overriding
Differences between method overloading and method overridingDifferences between method overloading and method overriding
Differences between method overloading and method overridingPinky Anaya
 
Introduction Of Linq , ASP.NET Training Ahmedabad, ASP.NET Course Ahmedabad
Introduction Of Linq , ASP.NET Training Ahmedabad, ASP.NET Course AhmedabadIntroduction Of Linq , ASP.NET Training Ahmedabad, ASP.NET Course Ahmedabad
Introduction Of Linq , ASP.NET Training Ahmedabad, ASP.NET Course AhmedabadNicheTech Com. Solutions Pvt. Ltd.
 
R Programming: Getting Help In R
R Programming: Getting Help In RR Programming: Getting Help In R
R Programming: Getting Help In RRsquared Academy
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answersAkash Gawali
 
Применение паттерна Page Object для автоматизации веб сервисов
Применение паттерна Page Object для автоматизации веб сервисовПрименение паттерна Page Object для автоматизации веб сервисов
Применение паттерна Page Object для автоматизации веб сервисовCOMAQA.BY
 
Function overloading and overriding
Function overloading and overridingFunction overloading and overriding
Function overloading and overridingRajab Ali
 

Was ist angesagt? (20)

Intake 38 5 1
Intake 38 5 1Intake 38 5 1
Intake 38 5 1
 
Language Integrated Query By Nyros Developer
Language Integrated Query By Nyros DeveloperLanguage Integrated Query By Nyros Developer
Language Integrated Query By Nyros Developer
 
Intake 38_1
Intake 38_1Intake 38_1
Intake 38_1
 
Language Integrated Query - LINQ
Language Integrated Query - LINQLanguage Integrated Query - LINQ
Language Integrated Query - LINQ
 
Module 3: Introduction to LINQ (PowerPoint Slides)
Module 3: Introduction to LINQ (PowerPoint Slides)Module 3: Introduction to LINQ (PowerPoint Slides)
Module 3: Introduction to LINQ (PowerPoint Slides)
 
Linq
LinqLinq
Linq
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
Differences between method overloading and method overriding
Differences between method overloading and method overridingDifferences between method overloading and method overriding
Differences between method overloading and method overriding
 
Intake 38 3
Intake 38 3Intake 38 3
Intake 38 3
 
Intake 37 1
Intake 37 1Intake 37 1
Intake 37 1
 
Templates
TemplatesTemplates
Templates
 
Class and object
Class and objectClass and object
Class and object
 
Introduction Of Linq , ASP.NET Training Ahmedabad, ASP.NET Course Ahmedabad
Introduction Of Linq , ASP.NET Training Ahmedabad, ASP.NET Course AhmedabadIntroduction Of Linq , ASP.NET Training Ahmedabad, ASP.NET Course Ahmedabad
Introduction Of Linq , ASP.NET Training Ahmedabad, ASP.NET Course Ahmedabad
 
Intake 37 2
Intake 37 2Intake 37 2
Intake 37 2
 
Linq to sql
Linq to sqlLinq to sql
Linq to sql
 
R Programming: Getting Help In R
R Programming: Getting Help In RR Programming: Getting Help In R
R Programming: Getting Help In R
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers
 
Применение паттерна Page Object для автоматизации веб сервисов
Применение паттерна Page Object для автоматизации веб сервисовПрименение паттерна Page Object для автоматизации веб сервисов
Применение паттерна Page Object для автоматизации веб сервисов
 
Templates
TemplatesTemplates
Templates
 
Function overloading and overriding
Function overloading and overridingFunction overloading and overriding
Function overloading and overriding
 

Andere mochten auch

Presentation to the Greely Business Association Members
Presentation to the Greely Business Association MembersPresentation to the Greely Business Association Members
Presentation to the Greely Business Association MembersKerry Mortimer
 
Bodas de sangre
Bodas de sangreBodas de sangre
Bodas de sangreparasubir
 
Municipal Alcohol Policy Guide--September 2015
Municipal Alcohol Policy Guide--September 2015Municipal Alcohol Policy Guide--September 2015
Municipal Alcohol Policy Guide--September 2015Erica Adams (Brooks)
 
Definitiva plantación das cinco árbores celtas
Definitiva plantación das cinco árbores celtasDefinitiva plantación das cinco árbores celtas
Definitiva plantación das cinco árbores celtasradiorasca
 
GDCR15 in Las Palmas, Gran Canaria
GDCR15 in Las Palmas, Gran CanariaGDCR15 in Las Palmas, Gran Canaria
GDCR15 in Las Palmas, Gran CanariaPeter Kofler
 
SÍLABO DE PRESUPUESTOS (5º NIVEL "A" VESP. CONT. Y AUD.) UTMACHALA
SÍLABO DE PRESUPUESTOS (5º NIVEL "A" VESP. CONT. Y AUD.) UTMACHALASÍLABO DE PRESUPUESTOS (5º NIVEL "A" VESP. CONT. Y AUD.) UTMACHALA
SÍLABO DE PRESUPUESTOS (5º NIVEL "A" VESP. CONT. Y AUD.) UTMACHALAAngel Berrones
 
Assessment and Appeals Process
Assessment and Appeals ProcessAssessment and Appeals Process
Assessment and Appeals Processfsbrlaw
 
Tratado de Sèvres lausana
Tratado de Sèvres   lausanaTratado de Sèvres   lausana
Tratado de Sèvres lausanaElenaCanizares
 
Business Model Canvas-Case Study in Burmese
Business Model Canvas-Case Study in BurmeseBusiness Model Canvas-Case Study in Burmese
Business Model Canvas-Case Study in BurmeseSai Lin Naung
 
Happy teachers day
Happy teachers dayHappy teachers day
Happy teachers dayMohit Goyal
 
Stem education by priti vats
Stem education  by priti vatsStem education  by priti vats
Stem education by priti vatsPriti Vats
 
FigthingHAI’s with environmental hygiene
FigthingHAI’s with environmental hygieneFigthingHAI’s with environmental hygiene
FigthingHAI’s with environmental hygieneLalema Inc.
 

Andere mochten auch (14)

Work Example
Work ExampleWork Example
Work Example
 
Presentation to the Greely Business Association Members
Presentation to the Greely Business Association MembersPresentation to the Greely Business Association Members
Presentation to the Greely Business Association Members
 
Bodas de sangre
Bodas de sangreBodas de sangre
Bodas de sangre
 
Municipal Alcohol Policy Guide--September 2015
Municipal Alcohol Policy Guide--September 2015Municipal Alcohol Policy Guide--September 2015
Municipal Alcohol Policy Guide--September 2015
 
Definitiva plantación das cinco árbores celtas
Definitiva plantación das cinco árbores celtasDefinitiva plantación das cinco árbores celtas
Definitiva plantación das cinco árbores celtas
 
GDCR15 in Las Palmas, Gran Canaria
GDCR15 in Las Palmas, Gran CanariaGDCR15 in Las Palmas, Gran Canaria
GDCR15 in Las Palmas, Gran Canaria
 
SÍLABO DE PRESUPUESTOS (5º NIVEL "A" VESP. CONT. Y AUD.) UTMACHALA
SÍLABO DE PRESUPUESTOS (5º NIVEL "A" VESP. CONT. Y AUD.) UTMACHALASÍLABO DE PRESUPUESTOS (5º NIVEL "A" VESP. CONT. Y AUD.) UTMACHALA
SÍLABO DE PRESUPUESTOS (5º NIVEL "A" VESP. CONT. Y AUD.) UTMACHALA
 
Assessment and Appeals Process
Assessment and Appeals ProcessAssessment and Appeals Process
Assessment and Appeals Process
 
Tratado de Sèvres lausana
Tratado de Sèvres   lausanaTratado de Sèvres   lausana
Tratado de Sèvres lausana
 
Propuestas de delegados
Propuestas de delegadosPropuestas de delegados
Propuestas de delegados
 
Business Model Canvas-Case Study in Burmese
Business Model Canvas-Case Study in BurmeseBusiness Model Canvas-Case Study in Burmese
Business Model Canvas-Case Study in Burmese
 
Happy teachers day
Happy teachers dayHappy teachers day
Happy teachers day
 
Stem education by priti vats
Stem education  by priti vatsStem education  by priti vats
Stem education by priti vats
 
FigthingHAI’s with environmental hygiene
FigthingHAI’s with environmental hygieneFigthingHAI’s with environmental hygiene
FigthingHAI’s with environmental hygiene
 

Ähnlich wie Intake 37 linq2

Visual studio 2008
Visual studio 2008Visual studio 2008
Visual studio 2008Luis Enrique
 
.Net Classes and Objects | UiPath Community
.Net Classes and Objects | UiPath Community.Net Classes and Objects | UiPath Community
.Net Classes and Objects | UiPath CommunityRohit Radhakrishnan
 
SVR17: Data-Intensive Computing on Windows HPC Server with the ...
SVR17: Data-Intensive Computing on Windows HPC Server with the ...SVR17: Data-Intensive Computing on Windows HPC Server with the ...
SVR17: Data-Intensive Computing on Windows HPC Server with the ...butest
 
SVR17: Data-Intensive Computing on Windows HPC Server with the ...
SVR17: Data-Intensive Computing on Windows HPC Server with the ...SVR17: Data-Intensive Computing on Windows HPC Server with the ...
SVR17: Data-Intensive Computing on Windows HPC Server with the ...butest
 
Certification preparation - Net classses and functions.pptx
Certification preparation - Net classses and functions.pptxCertification preparation - Net classses and functions.pptx
Certification preparation - Net classses and functions.pptxRohit Radhakrishnan
 
"Optimization of a .NET application- is it simple ! / ?", Yevhen Tatarynov
"Optimization of a .NET application- is it simple ! / ?",  Yevhen Tatarynov"Optimization of a .NET application- is it simple ! / ?",  Yevhen Tatarynov
"Optimization of a .NET application- is it simple ! / ?", Yevhen TatarynovFwdays
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstractionIntro C# Book
 
Whidbey old
Whidbey old Whidbey old
Whidbey old grenaud
 

Ähnlich wie Intake 37 linq2 (20)

Linq
LinqLinq
Linq
 
Client sidescripting javascript
Client sidescripting javascriptClient sidescripting javascript
Client sidescripting javascript
 
Visual studio 2008
Visual studio 2008Visual studio 2008
Visual studio 2008
 
B_110500002
B_110500002B_110500002
B_110500002
 
ORM - Ivan Marković
ORM - Ivan MarkovićORM - Ivan Marković
ORM - Ivan Marković
 
Mvc acchitecture
Mvc acchitectureMvc acchitecture
Mvc acchitecture
 
Express 070 536
Express 070 536Express 070 536
Express 070 536
 
Vb net1
Vb net1Vb net1
Vb net1
 
.Net Classes and Objects | UiPath Community
.Net Classes and Objects | UiPath Community.Net Classes and Objects | UiPath Community
.Net Classes and Objects | UiPath Community
 
SVR17: Data-Intensive Computing on Windows HPC Server with the ...
SVR17: Data-Intensive Computing on Windows HPC Server with the ...SVR17: Data-Intensive Computing on Windows HPC Server with the ...
SVR17: Data-Intensive Computing on Windows HPC Server with the ...
 
SVR17: Data-Intensive Computing on Windows HPC Server with the ...
SVR17: Data-Intensive Computing on Windows HPC Server with the ...SVR17: Data-Intensive Computing on Windows HPC Server with the ...
SVR17: Data-Intensive Computing on Windows HPC Server with the ...
 
Certification preparation - Net classses and functions.pptx
Certification preparation - Net classses and functions.pptxCertification preparation - Net classses and functions.pptx
Certification preparation - Net classses and functions.pptx
 
c++ referesher 1.pdf
c++ referesher 1.pdfc++ referesher 1.pdf
c++ referesher 1.pdf
 
Csharp generics
Csharp genericsCsharp generics
Csharp generics
 
"Optimization of a .NET application- is it simple ! / ?", Yevhen Tatarynov
"Optimization of a .NET application- is it simple ! / ?",  Yevhen Tatarynov"Optimization of a .NET application- is it simple ! / ?",  Yevhen Tatarynov
"Optimization of a .NET application- is it simple ! / ?", Yevhen Tatarynov
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
Java Lab Manual
Java Lab ManualJava Lab Manual
Java Lab Manual
 
Whidbey old
Whidbey old Whidbey old
Whidbey old
 
Unit 1
Unit  1Unit  1
Unit 1
 
JavaProgrammingManual
JavaProgrammingManualJavaProgrammingManual
JavaProgrammingManual
 

Mehr von Mahmoud Ouf

Mehr von Mahmoud Ouf (20)

Relation between classes in arabic
Relation between classes in arabicRelation between classes in arabic
Relation between classes in arabic
 
Intake 38 data access 5
Intake 38 data access 5Intake 38 data access 5
Intake 38 data access 5
 
Intake 38 data access 4
Intake 38 data access 4Intake 38 data access 4
Intake 38 data access 4
 
Intake 38 data access 1
Intake 38 data access 1Intake 38 data access 1
Intake 38 data access 1
 
Intake 38 12
Intake 38 12Intake 38 12
Intake 38 12
 
Intake 38 11
Intake 38 11Intake 38 11
Intake 38 11
 
Intake 38 10
Intake 38 10Intake 38 10
Intake 38 10
 
Intake 38 9
Intake 38 9Intake 38 9
Intake 38 9
 
Intake 38 8
Intake 38 8Intake 38 8
Intake 38 8
 
Intake 38 7
Intake 38 7Intake 38 7
Intake 38 7
 
Intake 38 6
Intake 38 6Intake 38 6
Intake 38 6
 
Intake 38 5
Intake 38 5Intake 38 5
Intake 38 5
 
Intake 38 4
Intake 38 4Intake 38 4
Intake 38 4
 
Intake 38 2
Intake 38 2Intake 38 2
Intake 38 2
 
Intake 37 DM
Intake 37 DMIntake 37 DM
Intake 37 DM
 
Intake 37 12
Intake 37 12Intake 37 12
Intake 37 12
 
Intake 37 11
Intake 37 11Intake 37 11
Intake 37 11
 
Intake 37 10
Intake 37 10Intake 37 10
Intake 37 10
 
Intake 37 9
Intake 37 9Intake 37 9
Intake 37 9
 
Intake 37 8
Intake 37 8Intake 37 8
Intake 37 8
 

Kürzlich hochgeladen

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 

Kürzlich hochgeladen (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 

Intake 37 linq2

  • 1. Language INtegrated Query (LINQ) Eng. Mahmoud Ouf Lecture 2 mmouf@2017
  • 2. Introduction To LINQ • Problems in accessing Data from Different DataSource: We Can’t programmatically interact with a database at the native language level Trouble caused by conflict data types utilized versus the native language of the program mmouf@2017
  • 3. LINQ • Microsoft’s technology to provide a language-level support mechanism for querying data of all types. in-memory arrays and collections, databases, XML documents, and more. • The returned Set of objects is called “sequence” • Most sequence are of type IEnumerable<T> • LINQ is not for query as in its name, We can better think of it as Data Integration Engine (DIE) mmouf@2017
  • 4. LINQ Definition • LINQ is a uniform programming model for any kind of data. • LINQ enables you to query and manipulate data with a consistent model that is independent from data sources. • LINQ is just another tool for embedding SQL queries into code. • LINQ is yet another data abstraction layer. LINQ is all the previous and more • LINQ is a methodology that simplifies and unifies the implementation of any kind of data access. • LINQ does not force you to use a specific architecture; it facilitates the implementation of several existing architectures for accessing data. mmouf@2017
  • 6. LINQ Query Expression • Query expressions are written in a declarative query syntax introduced in C# 3.0 • Use the same basic query expression patterns to query and transform data in SQL databases, ADO.NET Datasets, XML documents and streams, and .NET collections • All LINQ query operations consist of three distinct actions: 1. Obtain the data source. 2. Create the query. 3. Execute the query. mmouf@2017
  • 7. LINQ Query Expression • LINQ use deffered execution: • A query is not executed until you iterate over the query variable in a foreach statement, this is named deffered execution. • The benefit of this approach is that you are able to apply the same LINQ query multiple times to the same container, and rest assured you are obtaining the latest and greatest results mmouf@2017
  • 8. LINQ Query Expression • The general form of the query expression is: • from id in source • {Where condition | • Orderby ordering, ordering, ... [Ascending | Descending] } • Select expr | ; mmouf@2017
  • 9. LINQ Query Expression class LINQQueryExpressions { static void Main() { // Specify the data source. int[] scores = new int[] { 97, 92, 81, 60 }; // Define the query expression. IEnumerable<int> scoreQuery = from score in scores where score > 80 select score; // Execute the query. foreach (int i in scoreQuery) { Console.Write(i + " "); } mmouf@2017
  • 10. LINQ Query Expression //Make a change Scores[0] = 50; Console.WriteLine(); // Re-Execute the query. foreach (int i in scoreQuery) { Console.Write(i + " "); } } } // Output: 97 92 81 // 92 81 mmouf@2017
  • 11. LINQ and Implicitly Typed Local Variable static void QueryOverInts() { int[] numbers = {10, 20, 30, 40, 1, 2, 3, 8}; // Use implicit typing here... var subset = from i in numbers where i < 10 select i; // ...and here. foreach (var i in subset) Console.WriteLine("Item: {0} ", i); } mmouf@2017
  • 12. LINQ and Extension method LINQ provides an API known as standard query Methods to support the kinds of operations we’re accustomed to in SQL. All standard query methods, are actually methods of the System.Linq.Enumerable static class. The Enumerable type provides a set of methods that do not have a direct C# query operator shorthand notation, but are instead exposed as extension methods. These generic methods can be called to transform a result set in various manners (Reverse<>(), ToArray<>(), ToList<>(), etc.). Some are used to extract singletons from a result set, others perform various set operations (Distinct<>(), Union<>(), Intersect<>(), etc.), and still others aggregate results (Count<>(), Sum<>(), Min<>(), Max<>() mmouf@2017
  • 13. LINQ and Extension method static void GetCount() { string[] currentVideoGames = {"Morrowind", "BioShock", "Half Life 2: Episode 1", "The Darkness", "Daxter", "System Shock 2"}; // Get count from the query. int numb = (from g in currentVideoGames where g.Length > 6 orderby g select g).Count<string>(); // numb is the value 5. Console.WriteLine("{0} items honor the LINQ query.", numb); } mmouf@2017
  • 14. Returning the Result of a LINQ Query It is possible to define a field within a class (or structure) whose value is the result of a LINQ query. To do so, however, you cannot make use of implicit typing (as the var keyword cannot be used for fields), and the target of the LINQ query cannot be instance-level data; therefore, it must be static. class LINQBasedFieldsAreClunky { private static string[] currentVideoGames = {"Morrowind", "Uncharted 2", "Fallout 3", "Daxter", "System Shock 2"}; // Can’t use implicit typing here! Must know type of subset! private IEnumerable<string> subset = from g in currentVideoGames where g.Contains(" ") orderby g select g; mmouf@2017
  • 15. Returning the Result of a LINQ Query public void PrintGames() { foreach (var item in subset) { Console.WriteLine(item); } } } mmouf@2017
  • 16. Returning the Result of a LINQ Query Implicitly typed variables cannot be used to define parameters, return values, or fields of a class or structure. So, how you could return a query result to an external caller?. The answer is, it depends. If you have a result set consisting of strongly typed data, such as an array of strings or a List<T> of Cars, you could abandon the use of the var keyword and use a proper IEnumerable<T> or IEnumerable type class Program { static void Main(string[] args) { Console.WriteLine("***** LINQ Return Values *****n"); IEnumerable<string> subset = GetStringSubset(); foreach (string item in subset) { mmouf@2017
  • 17. Returning the Result of a LINQ Query Console.WriteLine(item); } Console.ReadLine(); } static IEnumerable<string> GetStringSubset() { string[] colors = {"Light Red", "Green","Yellow", "Dark Red", "Red", "Purple"}; // Note subset is an IEnumerable<string>-compatible object. IEnumerable<string> theRedColors = from c in colors where c.Contains("Red") select c; return theRedColors; } } mmouf@2017
  • 18. Extension Methods of Enumerable class The Enumerable class supports a set of extension methods that allows you to use two (or more) LINQ queries as the basis to find unions, differences, concatenations, and intersections of data. •Except Method Extension method, which will return a LINQ result set that contains the differences between two containers, which in this case, is the value Yugo: static void DisplayDiff() { List<string> myCars = new List<String> {"Yugo", "Aztec", "BMW"}; List<string> yourCars = new List<String>{"BMW", "Saab", "Aztec" }; var carDiff =(from c in myCars select c).Except(from c2 in yourCars select c2); Console.WriteLine("Here is what you don’t have, but I do:"); foreach (string s in carDiff) Console.WriteLine(s); // Prints Yugo. } mmouf@2017
  • 19. Extension Methods of Enumerable class •Intersect Method Extension method will return a result set that contains the common data items in a set of containers. For example, the following method returns the sequence Aztec and BMW: static void DisplayIntersection() { List<string> myCars = new List<String> { "Yugo", "Aztec", "BMW" }; List<string> yourCars = new List<String> { "BMW", "Saab", "Aztec" }; // Get the common members. var carIntersect = (from c in myCars select c).Intersect(from c2 in yourCars select c2); Console.WriteLine("Here is what we have in common:"); foreach (string s in carIntersect) Console.WriteLine(s); // Prints Aztec and BMW. } mmouf@2017
  • 20. Extension Methods of Enumerable class •Union Method Extension method returns a result set that includes all members of a batch of LINQ queries. Like any proper union, you will not find repeating values if a common member appears more than once. Therefore, the following method will print out the values Yugo, Aztec, BMW, and Saab: static void DisplayUnion() { List<string> myCars = new List<String> { "Yugo", "Aztec", "BMW" }; List<string> yourCars = new List<String> { "BMW", "Saab", "Aztec" }; // Get the union of these containers. var carUnion = (from c in myCars select c).Union(from c2 in yourCars select c2); Console.WriteLine("Here is everything:"); foreach (string s in carUnion) Console.WriteLine(s); // Prints all common members. } mmouf@2017
  • 21. Extension Methods of Enumerable class •Concat Method Extension method returns a result set that is a direct concatenation of LINQ result sets. For example, the following method prints out the results Yugo, Aztec, BMW, BMW, Saab, and Aztec: static void DisplayConcat() { List<string> myCars = new List<String> { "Yugo", "Aztec", "BMW" }; List<string> yourCars = new List<String> { "BMW", "Saab", "Aztec" }; var carConcat = (from c in myCars select c).Concat(from c2 in yourCars select c2); // Prints: Yugo Aztec BMW BMW Saab Aztec. foreach (string s in carConcat) Console.WriteLine(s); } mmouf@2017
  • 22. Extension Methods of Enumerable class •Distinct Method When you call the Concat() extension method, you could very well end up with redundant entries in the fetched result, which could be exactly what you want in some cases. However, in other cases, you might want to remove duplicate entries in your data. To do so, simply call the Distinct() extension method static void DisplayConcatNoDups() { List<string> myCars = new List<String> { "Yugo", "Aztec", "BMW" }; List<string> yourCars = new List<String> { "BMW", "Saab", "Aztec" }; var carConcat = (from c in myCars select c).Distinct(from c2 in yourCars select c2); // Prints: Yugo Aztec BMW Saab. foreach (string s in carConcat.Distinct()) Console.WriteLine(s); } mmouf@2017
  • 23. The Internal Representation of LINQ Query Statements At this point, we have been introduced to the process of building query expressions using various C# query operators (such as from, in, where, orderby, and select). Also, we discovered that some functionality of the LINQ to Objects API can be accessed only when calling extension methods of the Enumerable class. The truth of the matter, however, is that when compiled, the C# compiler actually translates all C# LINQ operators into calls on methods of the Enumerable class. A great many of the methods of Enumerable have been prototyped to take delegates as arguments. mmouf@2017
  • 24. Building Query Expressions Using the Enumerable Type and Lambda Expressions Consider the following QueryStringsWithEnumerableAndLambdas() method, which is processing the local string array now making direct use of the Enumerable extension methods. static void QueryStringsWithEnumerableAndLambdas() { string[] currentVideoGames = {"Morrowind", "Uncharted 2", "Fallout 3", "Daxter", "System Shock 2"}; // Build a query expression using extension methods // granted to the Array via the Enumerable type. var subset = currentVideoGames.Where(game => game.Contains(" ")).OrderBy(game => game).Select(game => game); mmouf@2017
  • 25. Building Query Expressions Using the Enumerable Type and Lambda Expressions // Print out the results. foreach (var game in subset) Console.WriteLine("Item: {0}", game); Console.WriteLine(); } mmouf@2017
  • 26. LINQ to Object •Linq and Array static void QueryOverStrings() { // Assume we have an array of strings. (Step 1) string[] currentVideoGames = {"Morrowind", "BioShock", "Half Life 2: Episode 1", "The Darkness", "Daxter", "System Shock 2"}; // Build a query expression to represent the items in the array // that have more than 6 letters. (Step 2) IEnumerable<string> subset = from g in currentVideoGames where g.Length > 6 orderby g select g; // Print out the results. (Step 3) foreach (string s in subset) Console.WriteLine("Item: {0}", s); } mmouf@2017
  • 27. LINQ to Object •Linq and Generic Collection class Car { public string PetName = string.Empty; public string Color = string.Empty; public int Speed; public string Make = string.Empty; } static void Main(string[] args) { // Make a List<> of Car objects using object init syntax. (Step 1) List<Car> myCars = new List<Car>() { new Car{ PetName = "Henry", Color = "Silver", Speed = 100, Make = "BMW"}, new Car{ PetName = "Daisy", Color = "Tan", Speed = 90, Make = "BMW"}, new Car{ PetName = "Mary", Color = "Black", Speed = 55, Make = "VW"}, new Car{ PetName = "Clunker", Color = "Rust", Speed = 5, Make = "Yugo"}, new Car{ PetName = "Melvin", Color = "White", Speed = 43, Make = "Ford"} }; mmouf@2017
  • 28. LINQ to Object •Linq and Generic Collection // Create a query expression . (Step 2) var fastCars = from c in myCars where c.Speed > 90 && c.Make == "BMW" select c; //Execute the Query. (Step 3) foreach (var car in fastCars) { Console.WriteLine("{0} is going too fast!", car.PetName); } } mmouf@2017
  • 29. LINQ to Object •Linq and Non-Generic Collection LINQ are designed to work with any type implementing IEnumerable<T>, The Non-Generic collection doesn’t implement IEnumerable<T>. So, need to transform it to a Generic Collection First class Car { public string PetName = string.Empty; public string Color = string.Empty; public int Speed; public string Make = string.Empty; } static void Main(string[] args) { // Make a List<> of Car objects using object init syntax. (Step 1) ArrayList<Car> myCars = new ArrayList<Car>() { new Car{ PetName = "Henry", Color = "Silver", Speed = 100, Make = "BMW"}, new Car{ PetName = "Daisy", Color = "Tan", Speed = 90, Make = "BMW"}, mmouf@2017
  • 30. LINQ to Object •Linq and Non-Generic Collection new Car{ PetName = "Mary", Color = "Black", Speed = 55, Make = "VW"}, new Car{ PetName = "Clunker", Color = "Rust", Speed = 5, Make = "Yugo"}, new Car{ PetName = "Melvin", Color = "White", Speed = 43, Make = "Ford"} }; // Transform ArrayList into an IEnumerable<T>-compatible type. IEnumerable<Car> myCarsEnum = myCars.OfType<Car>(); // Create a query expression . (Step 2) var fastCars = from c in myCarsEnum where c.Speed > 90 && c.Make == "BMW" select c; //Execute the query. (Step 3) foreach (var car in fastCars) Console.WriteLine("{0} is going too fast!", car.PetName); } mmouf@2017