我是新来的公司,使用 C#(我习惯使用其他语言),我刚刚在代码中遇到了一个 Lambda 表达式,所以我想了解它是如何工作的,但是关于the Microsoft website远未明确:
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);
}
}
在看“digits”的定义时,只看到内容,却无法理解为什么index
确实是字符串的索引。让我通过用 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);
}
}
=> 我怎么知道something
的意思是索引而不是 strings[]
的另一个属性?
相关问题:我可以向这个变量列表添加更多(为什么/为什么不)?
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);
}
}
=> 这似乎无法编译,存在语法错误,并显示以下消息:Delete 'Func<string,bool>' does not take 3 arguments
.为什么 bool
? index
不是 bool 值,而是整数。我错过了什么?
最佳答案
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.
是因为Where
重载了正在使用。
index
是 lambda 表达式中的参数 - lambda 表达式正在转换为 Func<string, int, bool>
.
来自documentation from this overload of Where
, predicate
参数:
A function to test each source element for a condition; the second parameter of the function represents the index of the source element.
参数值由调用委托(delegate)的代码提供。
您不能任意决定 lambda 表达式有多少个参数 - 您必须提供一个 lambda 表达式,该表达式可以转换为指定为 Where
的委托(delegate)类型方法参数。您可以只有一个参数(用于值)或两个(用于值和索引),因为该方法已重载。
关于C# 新手 : how to know the meaning of a variable in a lambda expression,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46970448/