Question

Could someone tell me what the difference / advantage is between the following 3 Find options:

        List<Employee> Employees = new List<Employee>();

        Employee tmp = new Employee();

        tmp.FirstName = "Randy";
        tmp.LastName = "Jones";
        Employees.Add(tmp);

        tmp.FirstName = "David";
        tmp.LastName = "Smith";
        Employees.Add(tmp);

        tmp.FirstName = "Michele";
        tmp.LastName = "Morris";
        Employees.Add(tmp);


        // Find option 1
        Employee eFound1= Employees.Find((Employee emp1) => {return emp1.LastName == "Jones";});

        // Find option 2
        Employee eFound2 = Employees.Find(emp2 => emp2.LastName == "Smith");

        // Find option 3
        Employee eFound3 = Employees.Find(
        delegate(Employee emp3)
        {
                return emp3.LastName == "Morris";
        }
        );

I have been reading about lambdas and predicates (which I suspect is somehow tied to the answer) but I can't put it all together. Any enlightenment would be appreciated!

Thanks David

Was it helpful?

Solution

The first is a statement lambda, the second one is a lambda expression and the third is an anonymous method.

They are all functionally equivalent.

OTHER TIPS

A predicate is a delegate to a method. In our next case, one that takes an int, and return a bool. this is what a predicate look like:

var numbers = Enumerable.Range(1,10);
var predicate = new Predicate<int>(pairNumber);
var pair_numbers = list.FindAll(predicate);

then you'll have somewhere this method that will be called:

bool pairNumber(int arg)
{
    return (arg % 2 == 0);
}

Achieving the same with lambdas, would be shorter, and will look like this:

var numbers = Enumerable.Range(1,10);
var pair_values = list.FindAll(val => val % 2 == 0);

Saving you the need to create the predicate with a method.

If it's a complex operation, I would prefer a method, so I can see what happens and work with it. If it's simple, lambda's all the way :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top