[C#] Using Lambda Expressions
All tutorials created in C# to be posted in here.
2 posts
Page 1 of 1
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
However, what if you only wanted to add monsters that had a health of 100 or more? Well one could write it like so
Also if you are a VB programmer one would write a Lambda expression as:
Function(<parameter> as dataType) statement
Entire Code for C#
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
And in there there are for variables name, health, damage per attack, and spawn rate.
public class monsterClass
{
}
Code: Select all
And in some other class you call this class and create some monsters
public class monsterClass
{
public string name;
public Int16 health;
public Int32 dmgPerAtk;
public float spawnRate;
}
Code: Select all
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
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 });
Code: Select all
However that is kind of bulky so instead let's use a lambda expression to condense it to one line
List<String> names = new List<String>();
foreach (monsterClass i in allMonsters)
names.Add(i.name);
/*
* Returns
*
* Dragon
* Goblin
* Wolves
* Wraiths
*/
Code: Select all
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. List<String> Names = allMonsters.Select(MONS => MONS.name).ToList();
/*
* Returns
*
* Dragon
* Goblin
* Wolves
* Wraiths
*/
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
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
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);
}}
Code: Select all
You can also change values of values such as, health or spawn rate, in code. My example would be
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);
Code: Select all
One could also use it as kind of an EventHandler such as in this piece of code
String response = Console.ReadLine();
monsterClass chosMons = allMonsters.Find(MONS => MONS.dmgPerAtk == Convert.ToInt32(response));
chosMons.dmgPerAtk += 5;
Console.WriteLine(chosMons.dmgPerAtk);
Code: Select all
However, I myself don't use it for that purpose public Form1()
{
InitializeComponent();
button1.Click += (sender, e) =>
{
MessageBox.Show("Cool cool");
};
}
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
Entire Code For VB
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;
}
}
Code: Select all
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! ;)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
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
Copyright Information
Copyright © Codenstuff.com 2020 - 2023