Unity’s C# environment includes access to .NET’s powerful LINQ querying expressions. In this post I’ll show how to use LINQ expressions to call anonymous functions.
Use the lambda
In the following examples, I’ll be using lambda expressions to specify anonymous functions that I will pass as arguments to the LINQ expressions.
C# uses the
=> symbol as an operator to create lambda expressions.
says, create an anonymous function taking a single argument
x and return the value of
x + 1.
Increment an array
Say I want to use my anonymous function to increment an array of counters when a tick passes in my game.
1 2 3 4 5 6 7 8 9 10 11
I could iterate over the array, incrementing each of the counters one at a time.
Or I could use LINQ expressions to map a function that increments an element over the array.
1 2 3
This approach has the benefit of avoiding an intermediate temporary variable to hold the returned array. It also avoids potential errors in writing the
for statement. It will never be off by one.
I find the use of higher order functional style, the LINQ expression, easier to read than the imperative style, the
One final thing to point out is that
Select() returns an
IEnumerable, so you have to call its
.ToArray method to return the proper integer array for the
Check out the example code on github.
I’ve only shown a tiny subset of the functionality that LINQ provides. Feel free to let me know if you dig in and find more useful tips.