Do you understand what this code block does:
You don’t?
Me neither. So let’s figure it out together.
Game Dev’s Guide to Lambda Expressions
If you're working with Unity and C# like me, you've probably heard of Lambda Expressions or at least seen their syntax on the internet. It's something I know exists and use here and there, but I didn’t really understand how it works. That’s why I wanted to dig a bit deeper and create this quick guide. Let’s go!
(Man, code blocs in Subtstack are terrible. I had to use screenshots for better readability, but it’s still doesn’t look good on mobile.)
What Are Lambda Expressions?
So basically, lambda expressions allow you to create functions without a name, or in technical terms, "anonymous functions." They let you write concise code without the need to define a separate method every time you need a simple function.
It’s like writing a mini-instruction instead of creating a big block of code.
It looks like this:
This expression takes a number “x” and adds 5 to it.
The left “()” part is used for parameters.
“=>” separates the parameters from the expression.
The right part (“x+5”) is the function, called expression.
Another example:
n => n * 2 to double each number in the numbers list.
ToList() converts the result to a List<int>.
The output will be: 2, 4, 6, 8, 10.
When to Use Lambda Expressions?
You can use them whenever you need a quick function but don’t want to write out a whole method for it. The most common uses include:
Filtering Data: They help you filter, sort, and transform data in lists and dictionaries. For example, you might want to select all enemies with health below a certain level, then sort them by level.
Events and Delegates: They make it easy to subscribe to events without needing a separate method. More on this later.
Lambda Expressions with LINQ
Lambda expressions and LINQ (Language-Integrated Query) are like best friends. LINQ allows you to query collections of data, and lambda expressions allow you to add logic within those queries. Let’s see some of the most common uses of lambda expressions with LINQ.
1. Where
The Where method allows you to filter elements in a collection based on a condition.
2. All
The All method checks if all elements in a collection satisfy a condition.
3. OrderBy/OrderByDescending
The OrderBy and OrderByDescending methods sort elements in a collection based on a key.
4. Take
The Take method selects a specified number of elements from a collection.
5. Select
The Select method projects each element of a sequence into a new form.
6. FirstOrDefault
The FirstOrDefault method returns the first element of a sequence that satisfies a condition, or a default value if no such element is found.
7. Other
Lambda Expressions with Events and Delegates
Lambda expressions are also useful when defining event handlers or delegate methods.
Let’s say you want to trigger an action when a button is clicked. Instead of defining a separate method, you can use a lambda expression:
Here, () => Debug.Log("Hellow world.") defines what should happen when the button is clicked.
Putting All Together
Now let’s go back to the first example:
Here’s what’s happening:
Where(e => e.IsActive && e.Health > 0): Filters the enemies list to only include those that are active and have health greater than 0.
OrderByDescending(e => e.Health): Sorts the filtered list in descending order based on health.
Take(5): Selects the top 5 enemies from the sorted list.
ToList(): Converts the result into a list.
Resources
As you might guess, this is just the tip of the iceberg. There’s no end to what you can do with Lambda. For more details, check out the sources below:
Lambda expressions and anonymous functions
Understanding Lambda Expressions in C#
Understand C# LAMBDA Expressions in only 2 minutes!
To-Do List
Watch: What Happens After The Big Game Dev Success?
Learn: How to be BIG in Japan
Play: 17 Fighters
Me
Reading: Zen and the Art of Motorcycle Maintenance by Robert M. Pirsig. A story of a motorcycle trip of the author and his son. It’s also a very thought-provoking trip since the author delves deeply into philosophical issues, like man's search for reason. What impressed me the most, however, is the writing style. It flows so naturally while also being detailed. Will try to learn from it.
Playing: I was playing Gothic 2, but my computer died and I lost all my progress just when I was finally getting stronger… Now I’m back to crawling on the ground.
Listening:
Thanks for reading!
And that’s it from today’s issue of GameDev’s Journey. I hope you enjoyed it and found it useful. If you did, please like and leave a comment. Reach out for suggestions, objections, questions, or just say hi.
But regardless, thank you so much for reading, and have a great game dev journey!
One very big benefit of lambdas is that you can declare functions as variables, function parameters, and even function return types. Very useful when embracing functional programming which focuses more on functions than objects from object oriented programming. In fact, it helps you create more generic, more testable code. But that's a more advanced topic.