Showing posts with label Lambda. Show all posts
Showing posts with label Lambda. Show all posts

Friday, October 4, 2013

LINQ : LINQPad

In my quest to get a better grasp of LINQ and Lambdas, I came across the “LinqPad” tool.  This free tool, written in 2007 but continually updated through the 3.5 .NET framework, was graciously written by Joseph Albahari and provides features up and beyond Linq.  Though the primary focus is Linq, this tool is excellent for testing your VB and C# snippets.  I have a numerous Visual Studio solutions just for testing code snippet and this tool easily wipes out most of them. 

At first, I had difficulty figuring out how to enter my syntax effectively but the incredibly helpful (and free) webinar from Albahari cleared up my questions in under an hour.  Attaching a datasource to the tool was very easy and with the extra features, such as importing namespaces, users can everything from data querying to C# code testing to testing RegEx to pinging websites.  

The tool also supports XML/XPath/XQuery, VB, F#, SQL, and ESQL.

 

Wednesday, October 2, 2013

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);
        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);
        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
public  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
//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  n  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  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):



Saturday, September 28, 2013

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<int, int> func = x => x / x;
    Console.WriteLine("Result is {0}", func(a));
    Console.ReadLine();
}



Result: