Thursday, May 7, 2015

Simple Lambda Expressions in C#

Intro

I'm not going to go too in-depth regarding Lambda expressions or how to use them in .Net. Rather, I will just show you a short sample to whet your appetite. If you've already used lambda expressions or LINQ then this post might not teach you much, but it's a short post so suffer through it if you can :)



Code samples are in VS2013, .Net 4.5. Other environments might work just fine too.

Example


using System;
using System.Collections.Generic;
using System.Linq;

namespace BlogLambda
{
    public class SomeClass
    {
        public int ANum;
        public string AString;

        public override string ToString()
        {
            return "(" + AString + ":" + ANum + ")";
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var things = new List<SomeClass>();
            things.Add(new SomeClass() { ANum = 2, AString = "cheese" });
            things.Add(new SomeClass() { ANum = 1, AString = "bacon" });
            things.Add(new SomeClass() { ANum = 7, AString = "tires" });
            things.Add(new SomeClass() { ANum = 4, AString = "apples" });
            var orderedThings1 = things.OrderBy(t => t.ANum);
            orderedThings1.ToList().ForEach(thing => Console.Write(thing));
            Console.WriteLine("---");
            var orderedThings2 = things.OrderBy(t => t.AString);
            orderedThings2.ToList().ForEach(thing => Console.Write(thing));
            Console.WriteLine("---");
            Console.ReadKey();
        }
    }
}


As promised, a pretty small sample. First we declare a new class called SomeClass. It's got 2 fields, and int and a string. It's got a single ToString method that we'll use just to illustrate what's going on.

The real meat here is within the Main() method (as you may have guessed, this is a console application). We first create a new list of objects of type SomeClass and initialize it with 4 new instances. Things get interesting on line 27, where we have our first lambda expression. The OrderBy method lets us sort the things object by whatever we tell it to sort. In this case we're sorting on the ANum property. If you haven't seen lambdas before the syntax might look a little weird. To me it helps if i think of "things.OrderBy(t => t.ANum)" meaning "sort things by t such that t.ANum". Basically I pretend that " => " means "such that". It's not always a great way to conceptualize, but it's helped me.

Moving on, you can see that we then output the list (notice the cool use of the ForEach extension method which allows us to spit out the whole list to the console, with a single line of code). We then sort the list a 2nd time on the AString field and send the output to the console once again. Here's the output:

(bacon:1)(cheese:2)(apples:4)(tires:7)---
(apples:4)(bacon:1)(cheese:2)(tires:7)---

That's all there is to it! First list sorted by ANum, second list sorted by AString.

What's Next?

Lambda expressions can get way more useful and way more complicated. I've barely even slightly rubbed the surface, much less scratched it. Read up on them! If you haven't tried LINQ yet, jump into that too. It can be a great time saver for us coder types.

Resources

dotnetperls Lambda

1 comment: