[C#] Using Lambda Expressions

All tutorials created in C# to be posted in here.
2 posts Page 1 of 1
Contributors
User avatar
SumCode
Dedicated Member
Dedicated Member
Posts: 57
Joined: Fri Aug 03, 2012 2:34 am

[C#] Using Lambda Expressions
SumCode
What is a Lambda expression?
A Lambda expression, according to MSDN, it is an anonymous function that you can use to create delegates or expression tree types. Now, that sounds very confusing, but I promise you will understand in a little.

Using the Lambda Expression:
To create a Lambda expression we use the lambda operator '=>'. On the left side of the operator would be your variable ('x' for example) and on the right would go your expression or statement, depending on the circumstance ('x == 5' for example).

When to Use the Lambda Expression:
Usually, when I use Lambda expressions, I use it when I want to loop through a list, of type, using Linq queries to get what I need. So, let's say for example you have a monsterClass
Code: Select all
    public class monsterClass
    {

    }
And in there there are for variables name, health, damage per attack, and spawn rate.
Code: Select all
    public class monsterClass
    {
        public string name;
        public Int16 health;
        public Int32 dmgPerAtk;
        public float spawnRate;
    }
And in some other class you call this class and create some monsters
Code: Select all
    List<monsterClass> allMonsters = new List<monsterClass>();
    allMonsters.Add(new monsterClass() { name = "Dragon", health = 100, dmgPerAtk = 10, spawnRate = 12F });
    allMonsters.Add(new monsterClass() { name = "Goblin", health = 200, dmgPerAtk = 5, spawnRate = 20F });
    allMonsters.Add(new monsterClass() { name = "Wolves", health = 50, dmgPerAtk = 5, spawnRate = 50F });
    allMonsters.Add(new monsterClass() { name = "Wraiths", health = 100, dmgPerAtk = 25, spawnRate = 5F });
Now you want to create a list of strings and in there you want to have the names of each monster. Normally, one would use a foreach statement and that would return
Code: Select all
    List<String> names = new List<String>();
    foreach (monsterClass i in allMonsters)
        names.Add(i.name);
    /*
        * Returns
        * 
        * Dragon
        * Goblin
        * Wolves
        * Wraiths
    */
However that is kind of bulky so instead let's use a lambda expression to condense it to one line
Code: Select all
    List<String> Names = allMonsters.Select(MONS => MONS.name).ToList();
    /*
        * Returns
        * 
        * Dragon
        * Goblin
        * Wolves
        * Wraiths
    */
So let's break that down. First, we start of by declaring a new list of strings which we called names. Then we said we want to select all 'name''s of monsters in 'allMonsters' and then we created a list version from the IEnumerable that Select returns.

However, what if you only wanted to add monsters that had a health of 100 or more? Well one could write it like so
Code: Select all
    List<String> names = new List<String>();

    //Lambda Expression
    allMonsters.ForEach((monsterClass MONS) => names.Add(MONS.health >= 100 ? MONS.name : null));
    names.RemoveAll(i => i == null);

    //ForEach Loop
    foreach (monsterClass i in allMonsters)
    {
        if (i.health >= 100)
            names.Add(i.name);
    }}
Another example of this could be if, say a user were to enter a new area in your map and you want to spawn monsters based on their spawn rates so I wrote this pretty simple code here
Code: Select all
    Console.WriteLine("Dragon\nGoblin\nWolves\nWraiths\nExit\nCheck to spawn a...");
    string a = Console.ReadLine();
    monsterClass monChosen = allMonsters.Find(MONS => MONS.name == a);
    spawnMonster(new Random().Next(0, 100) <= monChosen.spawnRate ? monChosen : null);
You can also change values of values such as, health or spawn rate, in code. My example would be
Code: Select all
    String response = Console.ReadLine();
    monsterClass chosMons = allMonsters.Find(MONS => MONS.dmgPerAtk == Convert.ToInt32(response));
    chosMons.dmgPerAtk += 5;
    Console.WriteLine(chosMons.dmgPerAtk);
One could also use it as kind of an EventHandler such as in this piece of code
Code: Select all
    public Form1()
    {
        InitializeComponent();
        button1.Click += (sender, e) =>
        {
            MessageBox.Show("Cool cool");
        };
    }
However, I myself don't use it for that purpose

Also if you are a VB programmer one would write a Lambda expression as:
Function(<parameter> as dataType) statement

Entire Code for C#
Code: Select all
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace Lambda_Expressions_Tut
{
    class Program
    {
        private static void Main(string[] args)
        {
            List<monsterClass> allMonsters = new List<monsterClass>();
            allMonsters.Add(new monsterClass() { name = "Dragon", health = 100, dmgPerAtk = 10, spawnRate = 12.0F });
            allMonsters.Add(new monsterClass() { name = "Goblin", health = 200, dmgPerAtk = 5, spawnRate = 100.0F });
            allMonsters.Add(new monsterClass() { name = "Wolves", health = 50, dmgPerAtk = 5, spawnRate = 50.0F });
            allMonsters.Add(new monsterClass() { name = "Wraiths", health = 100, dmgPerAtk = 25, spawnRate = 5.0F });

            List<String> names = new List<String>();

            //Lambda Expression
            allMonsters.ForEach((monsterClass MONS) => names.Add(MONS.health >= 100 ? MONS.name : null));
            names.RemoveAll(i => i == null);

            //ForEach Loop
            foreach (monsterClass i in allMonsters)
            {
                if (i.health >= 100)
                    names.Add(i.name);
            }

            Console.WriteLine(String.Join("\n", names));
        }
    }
    public class monsterClass
    {
        public string name;
        public Int16 health;
        public Int32 dmgPerAtk;
        public float spawnRate;
    }
}
Entire Code For VB
Code: Select all
Module Lambda_Expressions_Tut_VB

    Sub Main()
        Dim allMonsters As New List(Of monsterClass)

        allMonsters.Add(New monsterClass() With {.name = "Dragon", .health = 100, .dmgPerAtk = 10, .spawnRate = 12.0F})
        allMonsters.Add(New monsterClass() With {.name = "Goblin", .health = 200, .dmgPerAtk = 5, .spawnRate = 20.0F})
        allMonsters.Add(New monsterClass() With {.name = "Wolves", .health = 50, .dmgPerAtk = 5, .spawnRate = 50.0F})
        allMonsters.Add(New monsterClass() With {.name = "Wraiths", .health = 100, .dmgPerAtk = 25, .spawnRate = 5.0F})

        Dim names As New List(Of String)

        'Lambda Expression
        allMonsters.ForEach(Sub(MONS As monsterClass) names.Add(IIf(MONS.health >= 100, MONS.name, Nothing)))
        names.RemoveAll(Function(i As String) i = Nothing)

        'ForEach Loop
        For Each i As monsterClass In allMonsters
            If i.health >= 100 Then
                names.Add(i.name)
            End If
        Next
        Console.WriteLine(String.Join(vbNewLine, names))

    End Sub

End Module

Class monsterClass
    Public name As String
    Public health As Int16
    Public dmgPerAtk As Int32
    Public spawnRate As Single
End Class
Anyways just thought I would make this tutorial because I hardly ever see people using this expression despite how easy it makes things. Thanks for reading! ;)
User avatar
zachman61
VIP - Donator
VIP - Donator
Posts: 1891
Joined: Wed Dec 16, 2009 9:56 pm

Re: [C#] Using Lambda Expressions
zachman61
This is pretty interesting stuff, thanks #SumCode
Nailing my feet to the floor is easier than using my own muscles to balance, but you don't see me doing that :)
2 posts Page 1 of 1
Return to “C-Sharp Tutorials”