int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
var textNums =
from n in numbers
select strings[n];
Console.WriteLine("Number strings:");
foreach (var s in textNums)
{
Console.WriteLine(s);
}
如何使用 Lambda 表达式编写相同的代码....
numbers.ToList().ForEach(item => Console.WriteLine(strings[item]));
我假设你的意思是"from in"语句?
var textNs = numbers.Select(i => strings[i]);
var result=numbers.Select(n=>strings[n]);
这是正确的,但结果的类型为 IEnumerable< String >
。
这里,=>(lambda operator)
的左侧n
表示传递给函数的参数,右侧strings[n]
=>
表示函数体。
有关Linq和lambda表达式的更多信息,请参阅:http://www.codeproject.com/Articles/33769/Basics-of-LINQ-Lamda-Expressions
var result = numbers.Select(n => strings[n]);