繁体   English   中英

Lambda表达问题

[英]Lambda expression question

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变量只是一个计数器,它在遍历fruits列表时从0开始递增。 在这个例子中之间存在着某种天然的联系index的位置和fruitfruits ,你是通过迭代fruits一个元素在同一时间。

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

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

fruit是指当您遍历fruits的当前元素时。

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

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

index就是数组元素的索引。

不太确定您要问什么,请尝试:

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);
}

在Select的重载中使用Index来描述您的lambda当前正在迭代的对象的索引。

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

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

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

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

因此,如果您拥有(fruit,index)则:

fruit =数据对象。

index =数组中的索引。

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

也许分解一下此表达式的作用将有助于您理解它:

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

Select(...) =使用输入,如所示返回输出。

(fruit, index) =将选定的水果分配给可变fruit ,并将索引(在Enumerable中的位置(fruit, index)分配给index 如前所述,这只是您可以使用的一个重载(选项)。 如果您不在乎索引值,只需将其忽略即可。

=> =返回以下值

new { ... } =创建一个匿名类型的实例。 此类型将具有两个属性: indexstr index的值将是变量index str的值将是水果上子字符串的结果。

因此,如果您只想要水果,则可以这样重写它:

fruits.Select(fruit => fruit); 

如果您仍然想要索引,并带有水果的全名:

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

Select对于返回与输入内容不同的信息集很有用。

通过使用稍微复杂一些的场景作为示例:

例如,如果您有类似的类:

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); 

现在有意义吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM