LINQ : Use With Lambdas

The two examples below show two LINQ
queries utilizing Lambdas:
//First,
create  two  classes  that  we  will 
use  later
public 
class 
Rider
{
 
     
public 
string 
name;
 
     
public 
int 
number;
 
     
public 
override 
string 
ToString()
 
      {
 
             
return 
this.name;
 
      }

}

public 
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
//utility 
method  to  populate  list
public 
static 
List<Rider
createRider()
{
 
     
List<Rider
rl  = 
new 
List<Rider>();

 
     
Rider 
r  = 
new 
Rider();
 
      r.name 
“JorgeLorenzo”;
 
      r.number 
=  99;
 
      rl.Add(r);
 
     
new 
Rider();
 
      r.name 
“ValentinoRossi”;
 
      r.number 
=  46;
 
      rl.Add(r);

 
     
return 
rl;           
}

//utility 
method  to  populate  list
public 
static 
List<Team
createTeam()
{
 
     
List<Team
tl  = 
new 
List<Team>();

 
     
Team 
t  = 
new 
Team();
 
      t.teamName 
“Yamaha”;
 
      t.number 
=  99;
 
      tl.Add(t);
 
     
new 
Team();
 
      t.teamName 
“Yamaha”;
 
      t.number 
=  46;
 
      tl.Add(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
public 
static 
void 
linqLambdaRiders()
{
 
     
List<Rider
riders  =  createRider();         
           
 
                   
 
 
     
var 
linqQuery  =  riders.Select<
Rider
string>(r 
=>  r.name);

 
     
foreach 
(
var 
in 
linqQuery)
 
      {
 
             
Console.WriteLine(n);
 
      }
 
     
Console.ReadLine();
}

EXAMPLE
#1
//Use 
Linq  query  with  a  Lambda  expression 
to  list  riders
public 
static 
void 
linqLambdaRiders()
{
        List<Rider
riders  =  createRider();         
           
             
         
        var 
linqQuery  =  riders.Select<
Rider
string>(r 
=>  r.name);
        foreach 
(
var 
in 
linqQuery)
        {
             
 
Console.WriteLine(“Rider: 
{0}”

n);
        }
        Console.ReadLine();
}
RESULT #1:

EXAMPLE
#2

//Use 
joins  in  a  Linq  query  using  a 
Lambda  to  query  for  specific  riders
public 
static 
void 
linqLambdaRiderTeams()
{
        List<Rider
riders  =  createRider();
        List<Team
team  =  createTeam();
        //
        var 
linqQuery  =  riders.Join<
Rider
Team
int
Rider>
             
  (team, 
r1  =>  r1.number,  t  =>  t.number, 
(t,  r2)  =>  t);
        foreach 
(
var 
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
):

Lambda Expressions : An Introduction

One definition of a lambda, λ,
is the eleventh letter of the Greek alphabet and also has a value of
30 in the Greek numerical system. Another common usage is in
fraternity and sororities. Wikipedia gives at least twenty different
uses of the Lambda. Personally, the most awesome is the use of the
lambda is in calculus with the second greatest use of the Lambda
being in computer science. With the introduction of LINQ, lambda
usage has not only soared in code usage but the context is also easier to
understand.
Per MSDN,
“A lambda expression is an anonymous function that you can use to
create delegates or expression tree types. By using lambda
expressions, you can write local functions that can be passed as
arguments or returned as the value of function calls.” To learn
more about delegates, go here.

In .NET, the most basic lambda
expression can be recognized by its operator, “=>”, where
input parameters are on the left side of the operator and either an
expression or statement is on right side. For example, in the most
basic expression below, a parameter, “x” is passed in and the
returned result is the value of “x” squared:
EXAMPLE #1 – Basic Expression
Lambda :

//Simple Expression
Lambda:
delegate int del(int i);
public static void useDelegate()
{
    del d = x => x * x;
    int intParam = d(5);
    Console.WriteLine(“intParam now has a value of {0}.”, intParam);
    Console.ReadLine();
}
Result:
EXAMPLE #2 – Expression Lambda
with multiple parameters:

//Expression
Lambda returning a bool:
delegate bool del2(int i, string s);
public static void useTwoVariables()
{
    del2 d = (int x, string s) => s.Length > x;
    bool val = d(5, “ten”);
    Console.WriteLine(“The bool value of the expression is : {0}”, val);
    Console.ReadLine();  
}

Result:


EXAMPLE #3 – Statement Lambda:

//Statement
Lambda using strings to create a message
delegate void CreateMessage(string s);
public static void useStrings()
{
    CreateMessage cStr = x => { string s = x + ” “ + “is reigning MotoGP World Champion.”Console.WriteLine(s); };
    cStr(“Jorge Lorenzo, #99, “);
    Console.ReadLine();
}

Result:


EXAMPLE #3 – Using Lambda on
Generics:
//Use the Query
Operator func on generic delegates
public delegate TResult Func<TArg0, TResult>(TArg0 arg0);
public static void useFunc()
{
    int a = 15;
    Func<intint> func = x => x / x;
    Console.WriteLine(“Result is {0}”, func(a));
    Console.ReadLine();
}

Result:



LINQ : Query Using Cross & Group Joins

–Cross Join:

//LINQ Query Example For Cross Join
//This joins elements of two sequences based on equality of an element

public static void RiderBikeCrossJoinQuery()
{
//create a string array
string[] bikeWinners = new string[] {
    “Honda”“Yamaha”
};

//populate the Generic List
createRiders();
var linqQuery =
    from w in bikeWinners
    join r in riderList on w equals r.BikeMake
    select new { Winner = w, r.BikeModel, r.FirstName, r.LastName };

foreach (var win in linqQuery)
{
    Console.WriteLine(“Winner is {0} {1} on the {2} from {3}  “, win.FirstName, 
win.LastName,
win.BikeModel, win.Winner);
}

Console.ReadLine();

}
–Group Join:

//LINQ Query Example for Group Join
//This joins riders that have the same BikeMake

public static void RiderBikeGroupJoinQuery()
{
//create a string array
string[] bikeMake = new string[] {
    “Yamaha”“Ducati”
};

//populate the Generic List
createRiders();
var linqQuery =
    from b in bikeMake
    join r in riderList on b equals r.BikeMake into bm
    select new {Bikes = b, Models = bm}
    ;

foreach (var m in linqQuery)
{
    Console.WriteLine(m.Bikes + “:”);
    Console.WriteLine(“——————–“);               
    foreach (var x in m.Models)
    {
        Console.WriteLine(x.BikeModel);
    }
    Console.WriteLine();          
}

Console.ReadLine();

}

LINQ : Query Execution — Deferred vs Immediate

A LINQ query can be written to fetch
the results immediately or at a latter point in time. To keep it
simple, LINQ queries are often executed when the query is iterated
over (via a foreach loop) — as opposed to when the query variable is
created. This is considered a “deferred” execution; however,
queries can also be immediately executed when needed. For example,
immediate execution is useful when the query results need to be
cached or re-used.
From a syntax perspective, a query will
execute immediately when the query returns a singleton (Min, Max,
Count, Average, etc) or when it ends with .ToList, .ToArray,
.ToDictionary, etc.
Deferred Example:
public static void DelayedExecString()
{
       //Create some data
string[] bikes = new string[] { “Yamaha”“Honda”“Ducati”“Suzuki” };

//Build LINQ query
var simpleQuery =
    from bike in bikes
    select bike
    ;

//Query is NOW executed in a deferred manner
foreach (var type in simpleQuery)
{
    Console.WriteLine(“Bike type is {0}”, type);
}
Console.ReadLine();

}
Immediate Example:
public static void ImmediateExecString()
{
       //Create some data
string[] bikes = new string[] { “Yamaha”“Honda”“Ducati”“Suzuki” };
//Build LINQ query
var simpleQuery = (
    from bike in bikes
    select bike).ToList();  //Query is NOW executed immediately

foreach (var type in simpleQuery)
{
    Console.WriteLine(“Bike type is {0}”, type);
}

Console.ReadLine();

}

LINQ : Query A Class

The
following code creates a generic list based on a custom class and
then performs a LINQ query:
//Declare List Object
public static List<GPRider> riderList;

//Declare Class Object
public class GPRider
{
    public int Number { getset; }
    public string FirstName { getset; }
    public string LastName { getset; }
    public string Team { getset; }
    public string BikeMake { getset; }
    public string BikeModel { getset; }
}

//Create Data To Be Used
public static void createRiders()
{
    riderList = new List<GPRider>{
    new GPRider {Number=46, FirstName=“Valentino”, LastName=“Rossi”
        Team=“Factory Yamaha”, BikeMake=“Yamaha”, BikeModel=“M1”},
    new GPRider {Number=99, FirstName=“Jorge”, LastName=“Lorenzo”
        Team=“Factory Yamaha”, BikeMake=“Yamaha”, BikeModel=“M1”},
    new GPRider {Number=69, FirstName=“Nicky”, LastName=“Hayden”
        Team=“Factory Ducati”, BikeMake=“Ducati”, BikeModel=“DesmoGP13”},
    new GPRider {Number=35, FirstName =“Cal”, LastName=“Crutchlow”
        Team=“Tech 3”, BikeMake=“Yamaha”, BikeModel=“M1”}
    };
}
//Finally, LINQ Query Example For Generic List
public static void RiderQuery()
{
    //populate the Generic List
    createRiders();

    //create the LINQ query
    var linqQuery =
        from r in riderList
        select new { r.FirstName, r.LastName, r.Number, r.Team, 
            r.BikeMake, r.BikeModel };

    //Loop through LINQ query results
    foreach (var rider in linqQuery)
    {
        Console.WriteLine(“{0} {1}, #{2}, rides a {3} {4}, for the {5} team.”
            rider.FirstName, rider.LastName, rider.Number, rider.BikeMake, 
            rider.BikeModel, rider.Team);
    }

    Console.ReadLine();

}