Understand Lambda Expressions in 3 Minutes (Continuation)






3.45/5 (12 votes)
This is an alternative for "Understand Lambda Expressions in 3 minutes"
I like the Original-Tip very much, because it is short and clear, and what is explained is well explained. Please refer to it, otherwise this one is incomplete.
But I miss some important topics, that the article really meets its title "Understand Lambda..."
These are:
- Lambdas can be assigned to variables
- Can have several lines
- Can have several parameters
- Can be void
- Can have
return
-Statement
So here is a short glimpse how these mentioned features can look like:
void foo() {
List<int> numbers = new List<int> { 11, 13, 37, 52, 54, 88 }; // data
// original - sample
List<int> oddNumbers = numbers.Where(n => n % 2 == 1).ToList();
// original - lambda, assigned to a variable
Func<int, bool> isOdd = n => n % 2 == 1;
oddNumbers = numbers.Where(isOdd).ToList();
// complex sample, assigned, with lines, params, void, return-statement
var output = new List<string>();
Action<int, int> tryCreateLine = (i1, i2) => {
var result = i2 - i1;
if (result < 10) return; // reject create the line
output.Add(string.Format("{0} - {1} = {2}", i2, i1, result));
};
for (var i = 1; i < numbers.Count; i++) tryCreateLine(numbers[i - 1], numbers[i]);
MessageBox.Show(string.Join("\n", output), "calculations with result > 10");
}
The Messagebox-Output is as given below:
calculations with result > 10
---------------------------
37 - 13 = 24
52 - 37 = 15
88 - 54 = 34
I don't explain the code - it is self-explanatory. And you will recognize and understand each of the missing topics mentioned above.
You see: Lambdas support the complete C#-power - if wanted, one could write complete programs without any "normal" function.
But as the Original-Author already said:
Lambda expressions should be short. A complex definition makes the calling code difficult to read.