I'm new in a company, using C# (I'm used working with other languages), and I just encountered a Lambda expression in the code, so I'm trying to understand how this works, but the explanation on the Microsoft website is far from being clear:
static void Main(string[] args)
{
string[] digits = { "zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine" };
Console.WriteLine("Example that uses a lambda expression:");
var shortDigits = digits.Where((digit, index) => digit.Length < index);
foreach (var sD in shortDigits)
{
Console.WriteLine(sD);
}
}
When looking at the definition of "digits", I only see the content, but I can't understand why index
is indeed the index of the string. Let me explain you what I mean, by replacing the name of that variable by something
:
static void Main(string[] args)
{
string[] digits = { "zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine" };
Console.WriteLine("Example that uses a lambda expression:");
var shortDigits = digits.Where((digit, something) => digit.Length < something);
foreach (var sD in shortDigits)
{
Console.WriteLine(sD);
}
}
=> How can I know that the meaning of something
is the index and not another property of strings[]
?
Relevant question: can I add more to this list of variables (why/why not)?
static void Main(string[] args)
{
string[] digits = { "zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine" };
Console.WriteLine("Example that uses a lambda expression:");
var shortDigits = digits.Where((digit, var1, var2, ...) => digit.Length < var1);
foreach (var sD in shortDigits)
{
Console.WriteLine(sD);
}
}
=> This seems not to compile, there is a syntax error, with following message: Delete 'Func<string,bool>' does not take 3 arguments
. Why bool
? index
is not a Boolean, but an integer. What am I missing?
When looking at the definition of "digits", I only see the content, but I can't understand why index is indeed the index of the string.
It's because of the overload of Where
that's being used.
index
is a parameter in the lambda expression - the lambda expression is being converted into a Func<string, int, bool>
.
From the documentation from this overload of Where
, the predicate
parameter:
A function to test each source element for a condition; the second parameter of the function represents the index of the source element.
The parameter value is provided by the code that calls the delegate.
You don't get to decide arbitrarily how many parameters the lambda expression has - you have to provide a lambda expression that can be converted to the delegate type specified as the Where
method parameter. You can have just one parameter (for the value) or two (for the value and the index) because the method is overloaded.
See more on this question at Stackoverflow