lambda中的几个陈述

Nig*_*ker 0 .net c# lambda

我有以下声明

var evarage = productionreportentry
              .Sum(productionReportEntry => productionReportEntry.Cycletime);
Run Code Online (Sandbox Code Playgroud)

我想在Sum lambda中添加一些日志记录.这可能吗?

Ian*_*Ian 5

是的,做一些像:

var evarage = productionreportentry.Sum(productionReportEntry => 
{ 
   Trace.Writeline(productionReportEntry.Cycletime);
   return productionReportEntry.Cycletime;
});
Run Code Online (Sandbox Code Playgroud)

基本上你添加大括号,你需要显式返回lambda运行的值,在这种情况下是Cycletime,它被用作sum的一部分.

  • 请注意,这只适用于LINQ to Objects - 任何需要表达式树而不是委托的东西都会失败,因为语句lambdas无法转换为表达式树. (4认同)