Lambda表达问题

时间:2011-01-19 13:25:54

标签: .net linq lambda

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}
*/

有人可以解释一下,“index”如何与元素的数组索引相关联吗?

说,我需要一个查询,而不是第一个字母返回整个对象(在这种情况下为字符串)+相关索引。

7 个答案:

答案 0 :(得分:3)

index变量只是一个计数器,当您遍历fruits列表时,该计数器从0开始递增。在此示例中,indexfruitfruits的位置之间存在自然关系,因为您一次迭代fruits一个元素。

我不确定您有关访问“整个对象”的问题。您已经可以访问:

var query = fruits.Select((fruit, index) => new { index, fruit });
当你迭代它时,

fruit引用fruits中的当前元素。

答案 1 :(得分:1)

要在每种情况下返回整个字符串,只需修改查询:

var query =
    fruits.Select((fruit, index) =>
                  new { index, str = fruit });

index就是数组元素索引。

答案 2 :(得分:1)

不太确定你在问什么,但试试:

string[] fruits = { "apple", "banana", "mango", "orange", 
                      "passionfruit", "grape" };

var query =
    fruits.Select((fruit, index) =>
                      new { index, str = fruit });

foreach (var obj in query)
{
    Console.WriteLine("{0}", obj);
}

Index用于Select的重载,用于描述lambda当前迭代的对象的索引。

答案 3 :(得分:1)

这就是Select的特定重载如何工作:“函数的第二个参数表示源元素的索引”

如果您想要整个字符串,那么您可以执行以下操作:

var query = fruits.Select((fruit, index) => new { index, str = fruit });

答案 4 :(得分:1)

lambda表达式将第一个变量名称填充为项目本身,将第二个变量名称填充为索引。

所以如果你有(fruit,index)那么:

fruit =数据对象。

index =数组中的索引。

答案 5 :(得分:0)

关于你的第一个问题,它是Select的重载。请参阅:http://msdn.microsoft.com/en-us/library/bb534869.aspx

答案 6 :(得分:0)

或许打破这个表达式的作用将有助于你理解它:

fruits.Select((fruit, index) =>
                  new { index, str = fruit.Substring(0, index) });

Select(...) =使用输入,返回输出内的输出。

(fruit, index) =将选定的水果分配给变量fruit,将索引(位于Enumerable中的位置)分配到index。如上所述,这只是一个可用的重载(选项)。如果您不关心索引值,只需省略它。

=> =返回以下值

new { ... } =创建匿名类型的实例。此类型将包含两个属性:indexstrindex的值将是变量indexstr的值将是水果子串的结果。

所以,如果你只是想要水果,你可以像这样重写它:

fruits.Select(fruit => fruit); 

如果您仍想要索引,请使用水果的全名:

fruits.Select((fruit, index) =>
                  new { index, str = fruit});

选择对于从输入中返回不同的信息集非常有用。

通过示例使用稍微复杂的场景:

例如,如果你有这样的课程:

public class Customer { 
 public int Id {get; set;}
 public string Name { get; set;}
 public List<Order> Orders { get; set;} 
} 

public class Order { 
 public int Id { get;set;} 
 public double TotalOrderValue { get;set}
} 

您可以使用简单的Select语句返回客户,以及该客户订购量的总和:

 var customersTotalSpend = customers.Select(
      customer => 
      new { 
            customer, 
            TotalSpend = customer.Orders.Select(order => order.TotalOrderValue).Sum()
           }); 

如果我们想要的话,我们可以用TotalSpend值做一些事情,例如获得10个最大的消费者:

var biggestCustomers = customersTotalSpend.OrderByDescending(customerSpend=> customer.TotalSpend).Take(10); 

这现在有意义了吗?