Using Lambda Expressions & Some History

In this example I’m demonstrating some ways of finding an array element before .NET LINQ capabilities and how you can find elements now. I’ll demonstrate how a predicate, delegate, and LINQ lambda expressions can be used.

UsingLambdasProgram

 
Program.cs Code Contents

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyLinqAndCSharp
{
    class Program
    {
        /// <summary>
        /// Demonstrating some simple functional programming with lambdas along with some history
        /// on how far things have come.
        /// </summary>
        /// <param name="args"></param>

        static void Main(string[] args)
        {
            BeforeLinq();
            RunDelegate();
            RunLambda();

            Console.ReadLine();
        }

        // Private Methods
        //
        private static void BeforeLinq()
        {
            Console.WriteLine("****Running Before LINQ");

            // Before LINQ this was one way to find an object in a array. 
            var employees = createEmployeeArray();

            // Now let's find an employee in the array.
            // The main issue with this is if I wanted to find another name I would have to define another predicate method
            // for each item I wanted to search for.
            Employee daniel = Array.Find(employees, findDanielPredicate);
            try
            {
                Console.WriteLine(daniel.Name);
            }
            catch(Exception)
            {
                Console.WriteLine("The name cannot be found");
            }
            Console.WriteLine();
        }

        private static void RunDelegate()
        {
            Console.WriteLine("****Running The Delegate Option");

            // Creating our array.
            var employees = createEmployeeArray();

            // You can use a delegate and your predicate.
            // This query method can get pretty verbose before long though.
            Employee daniel = Array.Find(employees, 
                    delegate(Employee e)
                    {
                        return e.Name == "Daniel";
                    }
                );

            try
            {
                Console.WriteLine(daniel.Name);
            }
            catch(Exception)
            {
                Console.WriteLine("The name cannot be found");
            }
            Console.WriteLine();
        }

        private static void RunLambda()
        {
            Console.WriteLine("****Running The Lambda Expression****");

            // Creating the array.
            var employees = createEmployeeArray();

            // Using a lambda expression with the Array.Find method
            var daniel = Array.Find(employees, e => e.Name == "Daniel");

            try
            {
                Console.WriteLine(daniel.Name);
            }
            catch(Exception)
            {
                Console.WriteLine("The name cannot be found");
            }
            Console.WriteLine();
        }

        // For the predicate that's required for the Array.Find() method I have to create a named method.
        private static bool findDanielPredicate(Employee e)
        {
            return e.Name == "Daniel";
        }

        // Employees array to be used in various parts of this example.
        private static Employee[] createEmployeeArray()
        {
            Employee[] employees = new Employee[]
            {
                new Employee { ID = 1, Name = "Daniel"},        // You can change the Name property to see the error in action if need be.
                new Employee { ID = 2, Name = "Scott"},
                new Employee { ID = 3, Name = "Sara"}
            };
            return employees;
        }
    }
}

I’ve seperated out my examples into three different methods being called. The BeforeLinq, RunDelegate, and RunLambda methods. In each of them I’m creating an array of Employee objects.

In the BeforeLinq method I’m attempting to lookup an employee name by using an available method in Array.Find that takes an array and a predicate as the parameters. You’ll see that I’ve created a simple bool method to be used as the predicate parameter. You can see how this could be an issue. If I wanted to search for multiple items I would have to create a new predicate method for each one. Or come up with a fancy way to modify a single method. This can lead to writing a lot of code.

Another way with Array.Find is to use a delegate parameter. This will return a bool for the employee name that’s searched. Again, like the predicate, you would have to create mutiple delegates for the searches. The code this way can get pretty lenghty and confusing.

A much simpler way is to use LINQ expression with the Array.Find method as I’m showing in the RunLambda method. This really simplfies the the code when looking for elements by not forcing you to create predicate methods or delegates for each search.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s