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

Thursday, July 9, 2015

C# Anonymous Functions

Intro

Anonymous Functions: Things that activist hacker group does when they go into the potty room. Darn, I keep forgetting this is a programming blog! OK in this case an Anonymous Function is an "inline statement or expression that can be used wherever a delegate type is expected." (1). In layman's terms, rather than supplying a fully-defined function to a delegate, you can create an anonymous function within your normal code and use that. It's hard to explain, so let's see it in action.



Code Samples in VS2013, .Net 4.5.

Simple Use Case



using System;

namespace BlogAnonymousFunction
{
    public class Thingy
    {
        public string DoAThing(int val1, int val2, Func preProcessor = null)
        {
            int val3 = -1;
            if (preProcessor != null)
                val3 = preProcessor(val1, val2);
            return String.Format("val1:{0}, val2:{1}, val3: {2}", val1, val2, val3);
        }
    }
}


using System;

namespace BlogAnonymousFunction
{
    class Program
    {
        static void Main(string[] args)
        {
            var thingy = new Thingy();
            var result = thingy.DoAThing(24, 42, null);
            Console.WriteLine(result);
            result = thingy.DoAThing(24, 42, new Func((val1, val2) => val1 + val2));
            Console.WriteLine(result);
            Console.ReadKey();
        }
    }
}



A simple example to be certain. Our class Thingy has a single method DoAThing that accepts a function as a parameter. If the user passes in a value for this nullable function we will call it and set it to our 3rd value.

In the Main method we call DoAThing twice. First we call it once passing in a null function parameter. In the second call we pass in an anonymous function that adds the first and 2nd parameter, returning the result. You can see the results of our two function calls in the output window screenshot below.


Cool huh? Simple too, but it does take a few repetitions to get used to the odd syntax. Enjoy!

What's Next?

You can also do generic methods (no return type), you can create variables that reference a generic function/method, and more! Search on teh webs, you'll find plenty.

Resources

(1) Anonymous Functions
The Generic Func Delegates

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