string[] fruits = { "apple", "banana", "mango", "orange",
"passionfruit", "grape" };
var query =
fruits.Select((fruit, index) =>
new { index, str = fruit.Substring(0, index) });
foreach (var obj in query)
{
Console.WriteLine("{0}", obj);
}
/*
This code produces the following output:
{index=0, str=}
{index=1, str=b}
{index=2, str=ma}
{index=3, str=ora}
{index=4, str=pass}
{index=5, str=grape}
*/
有人可以解释一下,“索引”是如何作为元素的数组索引关联的?Lambda表达式问题
说,我需要一个查询,而不是第一个字母返回整个对象(在这种情况下字符串)+关联的索引。
你是什么意思“说,我需要一个查询,而不是第一个字母返回我整个对象(在这种情况下字符串)。” – 2011-01-19 13:29:50
我假设你要么学习语法,要么实际上需要更复杂的东西。否则,我假设你会使用一个简单的`foreach(var fruit in fruits)`循环并且完全跳过LINQ语法。 – 2011-01-19 13:35:33