Working with List in .Net 3.5

In this post I will be going over some of the features that were added or expanded upon in the release of .NET 3.5 and the usage of the lambda operator. I will start my tutorial off with the Exists() method which has a parameter of Predict<t> match. This is basically a really fancy way of saying this method does not want an object, it wants a method!

Now C# has even more flexibility in the way you choose to style your code design always remember all 3 of these solutions are the same.

public void LambaUsage()
    var intList = new List<int> {1, 2, 3, 4, 5, 10, 40, 50};

    bool exists = intList.Exists(Predicate);

private bool Predicate(int x)
    return x > 25;

This is the first way of calling Exists which is using a named method for the fact it has a physical name and declaration of method Predicate with a parameter of int and a return type of bool. Predicate will check if x > 25 returning true if it is, making Exists parameter the method Predicate will have it iterate through the list and try the Predicate over every object if it returns true for any case Exists will return true.

In C# 2.0 along with the inclusion of List and Generics that were added, they created anonymous methods. Personally I’ve always had issues remembering the syntax to write anonymous methods and without the help of Resharper I’d have been very frequently checking google for the usage of them. I’m sure you’ll be able to see why.

bool exists = intList.Exists(delegate(int x) { return x > 25; });

That sure is a lot of syntax to achieve the same thing that is defined in the named method, don’t you agree? The developers inside Microsoft obviously did too, that’s why they created the Lambda operator in C# 3.0. The Lambda operator makes writing anonymous methods for parameters much simpler and concise.

bool exists = intList.Exists(intVar => intVar > 25);

Always remember these 3 methods are interchangeable and no one way is better than another, it’s all semantical candy but personally and I feel most .NET developers willl agree the Lambda operator makes the most sense. In this statement intVar is an implicitly typed variable (in this case int), the Lambda operator => is saying to use intVar foreach object inside the list to do the method over => there.

So the Lambda operator has a variable and a method and operator creates an arrow towards the method that will use the variable. Not really the most scientific description but I think it’s very easy to remember that way.

More to come later today.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your 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