The two examples below show two LINQ
queries utilizing Lambdas:
queries utilizing Lambdas:
//First,
create two classes that we will
use later
create two classes that we will
use later
public
class
Rider
class
Rider
{
public
string
name;
public
int
number;
public
override
string
ToString()
{
return
this.name;
}
}
public
class
Team
class
Team
{
public
string
teamName;
public
int
number;
public
override
string
ToString()
{
return
this.teamName;
}
}
//Second,
add some data for the purpose of this example
add some data for the purpose of this example
//utility
method to populate list
method to populate list
public
static
List<Rider>
createRider()
static
List<Rider>
createRider()
{
List<Rider>
rl = new
List<Rider>();
Rider
r = new
Rider();
r.name
= “JorgeLorenzo”;
r.number
= 99;
rl.Add(r);
r
= new
Rider();
r.name
= “ValentinoRossi”;
r.number
= 46;
rl.Add(r);
return
rl;
}
//utility
method to populate list
method to populate list
public
static
List<Team>
createTeam()
static
List<Team>
createTeam()
{
List<Team>
tl = new
List<Team>();
Team
t = new
Team();
t.teamName
= “Yamaha”;
t.number
= 99;
tl.Add(t);
t
= new
Team();
t.teamName
= “Yamaha”;
t.number
= 46;
tl.Add(t);
t
= new
Team();
t.teamName
= “Ducati”;
t.number
= 69;
tl.Add(t);
return
tl;
}
//Now,
use Linq query with a Lambda
expression to list riders
use Linq query with a Lambda
expression to list riders
public
static
void
linqLambdaRiders()
static
void
linqLambdaRiders()
{
List<Rider>
riders = createRider();
var
linqQuery = riders.Select<Rider,
string>(r
=> r.name);
foreach
(var
n in
linqQuery)
{
Console.WriteLine(n);
}
Console.ReadLine();
}
EXAMPLE
#1
#1
//Use
Linq query with a Lambda expression
to list riders
Linq query with a Lambda expression
to list riders
public
static
void
linqLambdaRiders()
static
void
linqLambdaRiders()
{
List<Rider>
riders = createRider();
riders = createRider();
var
linqQuery = riders.Select<Rider,
string>(r
=> r.name);
linqQuery = riders.Select<Rider,
string>(r
=> r.name);
foreach
(var
n in
linqQuery)
(var
n in
linqQuery)
{
Console.WriteLine(“Rider:
{0}”,
n);
}
Console.ReadLine();
}
RESULT #1:
EXAMPLE
#2
#2
//Use
joins in a Linq query using a
Lambda to query for specific riders
joins in a Linq query using a
Lambda to query for specific riders
public
static
void
linqLambdaRiderTeams()
static
void
linqLambdaRiderTeams()
{
List<Rider>
riders = createRider();
riders = createRider();
List<Team>
team = createTeam();
team = createTeam();
//
var
linqQuery = riders.Join<Rider,
Team,
int,
Rider>
linqQuery = riders.Join<Rider,
Team,
int,
Rider>
(team,
r1 => r1.number, t => t.number,
(t, r2) => t);
foreach
(var
r in
linqQuery)
(var
r in
linqQuery)
{
Console.WriteLine(“Rider
in teams with matching number is
#{0}, {1}”,
r.number, r.name);
}
Console.ReadLine();
}
RESULT #2 (Note
that Rider #69 is excluded due to the join criteria):
that Rider #69 is excluded due to the join criteria):