59
Mohammad Shaker mohammadshaker.com C# Programming Course @ZGTRShaker 2011, 2012, 2013, 2014 C# Starter L05 – LINQ and Lambda Expressions

C# Starter L05-LINQ

Embed Size (px)

Citation preview

Page 1: C# Starter L05-LINQ

Mohammad Shakermohammadshaker.com

C# Programming Course@ZGTRShaker

2011, 2012, 2013, 2014

C# StarterL05 – LINQ and Lambda Expressions

Page 2: C# Starter L05-LINQ

LINQ

Page 3: C# Starter L05-LINQ

LINQOne of the most awesome things ever done!

Page 4: C# Starter L05-LINQ

LINQWhere’s Java?

Page 5: C# Starter L05-LINQ

LINQWhere’s Java?

2013 with some tool (not as good as .NET)

Page 6: C# Starter L05-LINQ

LINQstatic void Main(string[] args)

{string[] names = { "Alonso", "Zheng", "Smith", "Jones", "Smythe",

"Small", "Ruiz", "Hsieh", "Jorgenson", "Ilyich", "Singh", "Samba"};var queryResults = from n in names

where n.StartsWith("S")select n;

Console.WriteLine("Names beginning with S:");foreach (var item in queryResults) {

Console.WriteLine(item);}Console.Write("Program finished, press Enter/Return to continue:");Console.ReadLine();

}

Page 7: C# Starter L05-LINQ

LINQstatic void Main(string[] args)

{string[] names = { "Alonso", "Zheng", "Smith", "Jones", "Smythe",

"Small", "Ruiz", "Hsieh", "Jorgenson", "Ilyich", "Singh", "Samba"};var queryResults = from n in names

where n.StartsWith("S")select n;

Console.WriteLine("Names beginning with S:");foreach (var item in queryResults) {

Console.WriteLine(item);}Console.Write("Program finished, press Enter/Return to continue:");Console.ReadLine();

}

Page 8: C# Starter L05-LINQ

LINQstatic void Main(string[] args)

{string[] names = { "Alonso", "Zheng", "Smith", "Jones", "Smythe",

"Small", "Ruiz", "Hsieh", "Jorgenson", "Ilyich", "Singh", "Samba"};var queryResults = from n in names

where n.StartsWith("S")select n;

Console.WriteLine("Names beginning with S:");foreach (var item in queryResults) {

Console.WriteLine(item);}Console.Write("Program finished, press Enter/Return to continue:");Console.ReadLine();

}

List<string> queryResults = new List<string>();foreach (var item in names){

if (n.StartsWith(“S”)){

queryResults.Add(item);}

}

var queryResults = from n in nameswhere n.StartsWith("S")select n;

Page 9: C# Starter L05-LINQ

LINQstatic void Main(string[] args)

{string[] names = { "Alonso", "Zheng", "Smith", "Jones", "Smythe",

"Small", "Ruiz", "Hsieh", "Jorgenson", "Ilyich", "Singh", "Samba"};var queryResults = from n in names

where n.StartsWith("S")select n;

Console.WriteLine("Names beginning with S:");foreach (var item in queryResults) {

Console.WriteLine(item);}Console.Write("Program finished, press Enter/Return to continue:");Console.ReadLine();

}

List<string> queryResults = new List<string>();foreach (var item in names){

if (n.StartsWith(“S”)){

queryResults.Add(item);}

}

var queryResults = from n in nameswhere n.StartsWith("S")select n;

Page 10: C# Starter L05-LINQ

LINQstatic void Main(string[] args)

{string[] names = { "Alonso", "Zheng", "Smith", "Jones", "Smythe",

"Small", "Ruiz", "Hsieh", "Jorgenson", "Ilyich", "Singh", "Samba"};var queryResults = from n in names

where n.StartsWith("S")select n;

Console.WriteLine("Names beginning with S:");foreach (var item in queryResults) {

Console.WriteLine(item);}Console.Write("Program finished, press Enter/Return to continue:");Console.ReadLine();

}

List<string> queryResults = new List<string>();foreach (var item in names){

if (n.StartsWith(“S”)){

queryResults.Add(item);}

}

var queryResults = from n in nameswhere n.StartsWith("S")select n;

The SAME!

Page 11: C# Starter L05-LINQ

LINQstatic void Main(string[] args)

{string[] names = { "Alonso", "Zheng", "Smith", "Jones", "Smythe",

"Small", "Ruiz", "Hsieh", "Jorgenson", "Ilyich", "Singh", "Samba"};var queryResults = from n in names

where n.StartsWith("S")select n;

Console.WriteLine("Names beginning with S:");foreach (var item in queryResults) {

Console.WriteLine(item);}Console.Write("Program finished, press Enter/Return to continue:");Console.ReadLine();

}

List<string> queryResults = new List<string>();foreach (var item in names){

if (n.StartsWith(“S”)){

queryResults.Add(item);}

}

var queryResults = from n in nameswhere n.StartsWith("S")select n;

The SAME!

Page 12: C# Starter L05-LINQ

LINQstatic void Main(string[] args)

{string[] names = { "Alonso", "Zheng", "Smith", "Jones", "Smythe",

"Small", "Ruiz", "Hsieh", "Jorgenson", "Ilyich", "Singh", "Samba"};var queryResults = from n in names

where n.StartsWith("S")select n;

Console.WriteLine("Names beginning with S:");foreach (var item in queryResults) {

Console.WriteLine(item);}Console.Write("Program finished, press Enter/Return to continue:");Console.ReadLine();

}

Page 13: C# Starter L05-LINQ

LINQstatic void Main(string[] args)

{string[] names = { "Alonso", "Zheng", "Smith", "Jones", "Smythe",

"Small", "Ruiz", "Hsieh", "Jorgenson", "Ilyich", "Singh", "Samba"};var queryResults = from n in names

where n.StartsWith("S")select n;

Console.WriteLine("Names beginning with S:");foreach (var item in queryResults) {

Console.WriteLine(item);}Console.Write("Program finished, press Enter/Return to continue:");Console.ReadLine();

}

Names beginning with S:SmithSmytheSmallSinghSambaProgram finished, press Enter/Return to continue:

Page 14: C# Starter L05-LINQ

LINQstatic void Main(string[] args)

{string[] names = { "Alonso", "Zheng", "Smith", "Jones", "Smythe",

"Small", "Ruiz", "Hsieh", "Jorgenson", "Ilyich", "Singh", "Samba"};var queryResults = from n in names

select n;Console.WriteLine("Names beginning with S:");foreach (var item in queryResults) {

Console.WriteLine(item);}Console.Write("Program finished, press Enter/Return to continue:");Console.ReadLine();

}

Page 15: C# Starter L05-LINQ

LINQstatic void Main(string[] args)

{string[] names = { "Alonso", "Zheng", "Smith", "Jones", "Smythe",

"Small", "Ruiz", "Hsieh", "Jorgenson", "Ilyich", "Singh", "Samba"};var queryResults = from n in names

select n;Console.WriteLine("Names beginning with S:");foreach (var item in queryResults) {

Console.WriteLine(item);}Console.Write("Program finished, press Enter/Return to continue:");Console.ReadLine();

}

Names beginning with S:AlonsoZhengSmithJonesSmytheSmallRuizHsiehJorgensonIlyichSinghSambaProgram finished, press Enter/Return to continue:

Page 16: C# Starter L05-LINQ

LINQstatic void Main(string[] args)

{string[] names = { "Alonso", "Zheng", "Smith", "Jones", "Smythe",

"Small", "Ruiz", "Hsieh", "Jorgenson", "Ilyich", "Singh", "Samba"};var queryResults = from n in names

select n;Console.WriteLine("Names beginning with S:");foreach (var item in queryResults) {

Console.WriteLine(item);}Console.Write("Program finished, press Enter/Return to continue:");Console.ReadLine();

}

Names beginning with S:AlonsoZhengSmithJonesSmytheSmallRuizHsiehJorgensonIlyichSinghSambaProgram finished, press Enter/Return to continue:

Page 17: C# Starter L05-LINQ

Lambda Expressions

Page 18: C# Starter L05-LINQ

Tons of code in a line

Page 19: C# Starter L05-LINQ

Lambda Expressions

• The operator => is called the lambda operator.

n => n < 1000

“ Lambda ” comes from the lambda calculus, the mathematical formalism underlying

functional programming languages, which are the kind of programming on which LINQ is

based. If you are interested, check out sources such as the Wikipedia article on lambda

calculus. You don ’ t need to understand the mathematics to use lambda functions, although

understanding functional programming is helpful for advanced LINQ programming.

Page 20: C# Starter L05-LINQ

Lambda Expressions

var queryResults = from n in nameswhere n.StartsWith("S")select n;

Page 21: C# Starter L05-LINQ

Lambda Expressions

n => n.StartsWith(“S”)

var queryResults = from n in nameswhere n.StartsWith("S")select n;

Page 22: C# Starter L05-LINQ

Lambda Expressions

n => n.StartsWith(“S”)

var queryResults = from n in nameswhere n.StartsWith("S")select n;

Page 23: C# Starter L05-LINQ

Lambda Expressions

static void Main(string[] args){

string[] names = { "Alonso", "Zheng", "Smith", "Jones", "Smythe","Small", "Ruiz", "Hsieh", "Jorgenson", "Ilyich", "Singh", "Samba"};

var queryResults = names.Where(n => n.StartsWith("S"));Console.WriteLine("Names beginning with S:");

foreach (var item in queryResults) {

Console.WriteLine(item);}

Console.Write("Program finished, press Enter/Return to continue:");Console.ReadLine();

}

Page 24: C# Starter L05-LINQ

Lambda Expressions

static void Main(string[] args){

string[] names = { "Alonso", "Zheng", "Smith", "Jones", "Smythe","Small", "Ruiz", "Hsieh", "Jorgenson", "Ilyich", "Singh", "Samba"};

var queryResults = names.Where(n => n.StartsWith("S"));Console.WriteLine("Names beginning with S:");

foreach (var item in queryResults) {

Console.WriteLine(item);}

Console.Write("Program finished, press Enter/Return to continue:");Console.ReadLine();

}

Page 25: C# Starter L05-LINQ

Lambda Expressions

static void Main(string[] args){

string[] names = { "Alonso", "Zheng", "Smith", "Jones", "Smythe","Small", "Ruiz", "Hsieh", "Jorgenson", "Ilyich", "Singh", "Samba"};

var queryResults = names.Where(n => n.StartsWith("S"));Console.WriteLine("Names beginning with S:");

foreach (var item in queryResults) {

Console.WriteLine(item);}

Console.Write("Program finished, press Enter/Return to continue:");Console.ReadLine();

}

Names beginning with S:SmithSmytheSmallSinghSambaProgram finished, press Enter/Return to continue:

Page 26: C# Starter L05-LINQ

Query Techniques

Page 27: C# Starter L05-LINQ

Ordering Query Results

static void Main(string[] args){

string[] names = { "Alonso", "Zheng", "Smith", "Jones", "Smythe","Small", "Ruiz", "Hsieh", "Jorgenson", "Ilyich", "Singh", "Samba"};

var queryResults = from n in nameswhere n.StartsWith("S")orderby nselect n;

Console.WriteLine("Names beginning with S:");

foreach (var item in queryResults) {

Console.WriteLine(item);}

Console.Write("Program finished, press Enter/Return to continue:");Console.ReadLine();

}

Page 28: C# Starter L05-LINQ

Ordering Query Results

static void Main(string[] args){

string[] names = { "Alonso", "Zheng", "Smith", "Jones", "Smythe","Small", "Ruiz", "Hsieh", "Jorgenson", "Ilyich", "Singh", "Samba"};

var queryResults = from n in nameswhere n.StartsWith("S")orderby nselect n;

Console.WriteLine("Names beginning with S:");

foreach (var item in queryResults) {

Console.WriteLine(item);}

Console.Write("Program finished, press Enter/Return to continue:");Console.ReadLine();

}

Names beginning with S:SambaSinghSmallSmithSmytheProgram finished, press Enter/Return to continue:

Page 29: C# Starter L05-LINQ

Ordering Query Results

• Descending order

• This orders the example results as follows:

orderby n descending

SmytheSmithSmallSinghSamba

Page 30: C# Starter L05-LINQ

Ordering Query Results

• Ordering Using Method Syntax

var queryResults = names.OrderBy(n => n).Where(n => n.StartsWith(“S”));

static void Main(string[] args){

string[] names = { "Alonso", "Zheng", "Smith", "Jones", "Smythe","Small", "Ruiz", "Hsieh", "Jorgenson", "Ilyich", "Singh", "Samba"};

var queryResults = names.OrderBy(n => n).Where(n => n.StartsWith("S"));

Console.WriteLine("Names beginning with S:");

foreach (var item in queryResults) {

Console.WriteLine(item);}

Console.Write("Program finished, press Enter/Return to continue:");Console.ReadLine();

}

Page 31: C# Starter L05-LINQ

Ordering Query Results

• Ordering Using Method Syntax

var queryResults = names.OrderBy(n => n).Where(n => n.StartsWith(“S”));

static void Main(string[] args){

string[] names = { "Alonso", "Zheng", "Smith", "Jones", "Smythe","Small", "Ruiz", "Hsieh", "Jorgenson", "Ilyich", "Singh", "Samba"};

var queryResults = names.OrderBy(n => n).Where(n => n.StartsWith("S"));

Console.WriteLine("Names beginning with S:");

foreach (var item in queryResults) {

Console.WriteLine(item);}

Console.Write("Program finished, press Enter/Return to continue:");Console.ReadLine();

}

Names beginning with S:SambaSinghSmallSmithSmytheProgram finished, press Enter/Return to continue:

Page 32: C# Starter L05-LINQ

Ordering Query Results

• Ordering Using Method Syntax

var queryResults = names.OrderBy(n => n).Where(n => n.StartsWith(“S”));

static void Main(string[] args){

string[] names = { "Alonso", "Zheng", "Smith", "Jones", "Smythe","Small", "Ruiz", "Hsieh", "Jorgenson", "Ilyich", "Singh", "Samba"};

var queryResults = names.OrderBy(n => n).Where(n => n.StartsWith("S"));

Console.WriteLine("Names beginning with S:");

foreach (var item in queryResults) {

Console.WriteLine(item);}

Console.Write("Program finished, press Enter/Return to continue:");Console.ReadLine();

}

Names beginning with S:SambaSinghSmallSmithSmytheProgram finished, press Enter/Return to continue:

IOrderedEnumerable < string > and IEnumerable < string >

Page 33: C# Starter L05-LINQ

Ordering Query Results

• Descending order

var queryResults = names.OrderByDescending(n => n).Where(n => n.StartsWith(“S”));

Page 34: C# Starter L05-LINQ

Ordering Query Results

• What does this do?

var queryResults =names.OrderBy(n => n.Substring(n.Length-1)).Where(n => n.StartsWith(“S”));

Page 35: C# Starter L05-LINQ

Ordering Query Results

• What does this do?

var queryResults =names.OrderBy(n => n.Substring(n.Length-1)).Where(n => n.StartsWith(“S”));

Page 36: C# Starter L05-LINQ

Ordering Query Results

• What does this do?

var queryResults =names.OrderBy(n => n.Substring(n.Length-1)).Where(n => n.StartsWith(“S”));

Page 37: C# Starter L05-LINQ

Querying Complex Objects

Page 38: C# Starter L05-LINQ

Querying Complex Objectsclass Customer{

public string ID { get; set; }public string City { get; set; }public string Country { get; set; }public string Region { get; set; }public decimal Sales { get; set; }

}

Page 39: C# Starter L05-LINQ

Querying Complex Objectsstatic void Main(string[] args){

List < Customer > customers = new List < Customer > {

new Customer { ID=”A”, City=”New York”, Country=”USA”,Region=”North America”, Sales=9999},new Customer { ID=”B”, City=”Mumbai”, Country=”India”,Region=”Asia”, Sales=8888 },new Customer { ID=”C”, City=”Karachi”, Country=”Pakistan”,Region=”Asia”, Sales=7777 },new Customer { ID=”D”, City=”Delhi”, Country=”India”,Region=”Asia”, Sales=6666 },new Customer { ID=”E”, City=”S ã o Paulo”, Country=”Brazil”,Region=”South America”, Sales=5555 },new Customer { ID=”F”, City=”Moscow”, Country=”Russia”,Region=”Europe”, Sales=4444 },…

};

var queryResults =from c in customerswhere c.Region == “Asia”select c;

Console.WriteLine(“Customers in Asia:”);foreach (Customer c in queryResults){

Console.WriteLine(c);}

Console.Write(“Program finished, press Enter/Return to continue:”);Console.ReadLine();

}

Page 40: C# Starter L05-LINQ

Querying Complex Objects

• The output:

• Why?!

– Because ToString() is called for each Customer object. ToString() Is inherited directly

from the object class.

• Solution: Override the ToString() method.

Customers in Asia:CSharpCourse2011.CustomerCSharpCourse2011.CustomerCSharpCourse2011.CustomerCSharpCourse2011.CustomerCSharpCourse2011.CustomerCSharpCourse2011.CustomerCSharpCourse2011.CustomerCSharpCourse2011.CustomerCSharpCourse2011.CustomerCSharpCourse2011.CustomerProgram finished, press Enter/Return to continue:

Page 41: C# Starter L05-LINQ

Querying Complex Objects

• From this:

• To this:class Customer{

public string ID { get; set; }public string City { get; set; }public string Country { get; set; }public string Region { get; set; }public decimal Sales { get; set; }

public override string ToString(){

return “ID: “ + ID + “ City: “ + City + “ Country: “ + Country +“ Region: “ + Region + “ Sales: “ + Sales;

}}

class Customer{

public string ID { get; set; }public string City { get; set; }public string Country { get; set; }public string Region { get; set; }public decimal Sales { get; set; }

}

Page 42: C# Starter L05-LINQ

Querying Complex Objects

• The output now is:

Customers in Asia:ID: B City: Mumbai Country: India Region: Asia Sales: 8888ID: C City: Karachi Country: Pakistan Region: Asia Sales: 7777ID: D City: Delhi Country: India Region: Asia Sales: 6666ID: G City: Seoul Country: Korea Region: Asia Sales: 3333ID: H City: Istanbul Country: Turkey Region: Asia Sales: 2222ID: I City: Shanghai Country: China Region: Asia Sales: 1111ID: L City: Jakarta Country: Indonesia Region: Asia Sales: 3000ID: M City: Tokyo Country: Japan Region: Asia Sales: 4000ID: P City: Tehran Country: Iran Region: Asia Sales: 7000ID: R City: Beijing Country: China Region: Asia Sales: 9000Program finished, press Enter/Return to continue:

Page 43: C# Starter L05-LINQ

Querying Complex Objects

var queryResults =from c in customerswhere c.Region == “Asia”select c.City;

MumbaiKarachiDelhiSeoulIstanbulShanghaiJakartaTokyoTehranBeijing

Page 44: C# Starter L05-LINQ

Selecting Multiple Properties

Page 45: C# Starter L05-LINQ

Querying Complex Objects

• Let’s see this:

select c.City, c.Country, c.Sales

Page 46: C# Starter L05-LINQ

Querying Complex Objects

• Let’s see this:

• It’s an error. Unlike in SQL, LINQ does not allow multiple fields in a select clause!

– So, what’s the solution?

• Just creating a new object on-the-fly in the select clause to hold the results you want for your query!

select c.City, c.Country, c.Sales

Page 47: C# Starter L05-LINQ

Querying Complex Objects

• Let’s see this:

• It’s an error. Unlike in SQL, LINQ does not allow multiple fields in a select clause!

– So, what’s the solution?

• Just creating a new object on-the-fly in the select clause to hold the results you want for your query!

select c.City, c.Country, c.Sales

var queryResults =from c in customerswhere c.Region == “North America”select new { c.City, c.Country, c.Sales };

foreach (var item in queryResults){

Console.WriteLine(item);}

Page 48: C# Starter L05-LINQ

Querying Complex Objects

• Let’s see this:

• It’s an error. Unlike in SQL, LINQ does not allow multiple fields in a select clause!

– So, what’s the solution?

• Just creating a new object on-the-fly in the select clause to hold the results you want for your query!

select c.City, c.Country, c.Sales

var queryResults =from c in customerswhere c.Region == “North America”select new { c.City, c.Country, c.Sales };

foreach (var item in queryResults){

Console.WriteLine(item);}

{ City = New York, Country = USA, Sales = 9999 }{ City = Mexico City, Country = Mexico, Sales = 2000 }{ City = Los Angeles, Country = USA, Sales = 5000 }Program finished, press Enter/Return to continue:

Page 49: C# Starter L05-LINQ

Querying Complex Objects

• Now, instead of all this:

• Let’s try this:

var queryResults = customers.Where(c => c.Region == “North America”).Select(c => new { c.City, c.Country, c.Sales });

var queryResults =from c in customerswhere c.Region == “North America”select new { c.City, c.Country, c.Sales };

foreach (var item in queryResults){

Console.WriteLine(item);}

Page 50: C# Starter L05-LINQ

Querying Complex Objects

• Now, instead of all this:

• Let’s try this:

var queryResults = customers.Where(c => c.Region == “North America”).Select(c => new { c.City, c.Country, c.Sales });

{ City = New York, Country = USA, Sales = 9999 }{ City = Mexico City, Country = Mexico, Sales = 2000 }{ City = Los Angeles, Country = USA, Sales = 5000 }Program finished, press Enter/Return to continue:

var queryResults =from c in customerswhere c.Region == “North America”select new { c.City, c.Country, c.Sales };

foreach (var item in queryResults){

Console.WriteLine(item);}

Page 51: C# Starter L05-LINQ

Querying Complex Objects

• Now, instead of this:

• Let’s try this:

var queryResults = customers.Select(c => new { c.City, c.Country, c.Sales }).Where(c => c.Region == “North America”);

var queryResults = customers.Where(c => c.Region == “North America”).Select(c => new { c.City, c.Country, c.Sales });

Page 52: C# Starter L05-LINQ

Querying Complex Objects

• Now, instead of this:

• Let’s try this:

• It’s a Compiler Error! Because: The Region property is not included in the

anonymous type.

{c.City, c.Country, c.Sales } created by the Select() projection. The

compiler doesn’t know it yet!

var queryResults = customers.Select(c => new { c.City, c.Country, c.Sales }).Where(c => c.Region == “North America”);

var queryResults = customers.Where(c => c.Region == “North America”).Select(c => new { c.City, c.Country, c.Sales });

Page 53: C# Starter L05-LINQ

Querying Complex Objects

• OK, now, instead of this:

• Let’s try this:

var queryResults = customers.Select(c => new { c.City, c.Country, c.Sales }).Where(c => c.City == “New York”);

var queryResults = customers.Where(c => c.Region == “North America”).Select(c => new { c.City, c.Country, c.Sales });

Page 54: C# Starter L05-LINQ

Querying Complex Objects

• OK, now, instead of this:

• Let’s try this:

• Works beautifully!

var queryResults = customers.Select(c => new { c.City, c.Country, c.Sales }).Where(c => c.City == “New York”);

var queryResults = customers.Where(c => c.Region == “North America”).Select(c => new { c.City, c.Country, c.Sales });

Page 55: C# Starter L05-LINQ

Querying Complex Objects

• Distinct

var queryResults = customers.Select(c => c.Region).Distinct();

var queryResults = (from c in customers select c.Region).Distinct();

Page 56: C# Starter L05-LINQ

Ordering By Multiple Levels

Page 57: C# Starter L05-LINQ

Ordering By Multiple Levels

var queryResults =from c in customersorderby c.Region, c.Country, c.Cityselect new { c.ID, c.Region, c.Country, c.City };

Page 58: C# Starter L05-LINQ

Ordering By Multiple Levels

var queryResults =from c in customersorderby c.Region, c.Country, c.Cityselect new { c.ID, c.Region, c.Country, c.City };

{ ID = O, Region = Africa, Country = Egypt, City = Cairo }{ ID = J, Region = Africa, Country = Nigeria, City = Lagos }{ ID = R, Region = Asia, Country = China, City = Beijing }{ ID = I, Region = Asia, Country = China, City = Shanghai }{ ID = D, Region = Asia, Country = India, City = Delhi }{ ID = B, Region = Asia, Country = India, City = Mumbai }{ ID = L, Region = Asia, Country = Indonesia, City = Jakarta }{ ID = P, Region = Asia, Country = Iran, City = Tehran }{ ID = M, Region = Asia, Country = Japan, City = Tokyo }{ ID = G, Region = Asia, Country = Korea, City = Seoul }….

Page 59: C# Starter L05-LINQ

Drilling further

• Many other techniques

• Grouping

• Joining

• Take

• Skip

• ….