用于查询的Lambda表达式根据条件选择不同的值

时间:2010-11-15 08:11:51

标签: c# lambda

我正在使用c#中的lambda表达式。我试图根据类型选择一个值,然后将结果相加。

var  length = (from al in tmp
                from n in al
                 where n.TripPath.DataType =="type1" || n.tripPath.DataType == "Type2"
                 select n.trippath.length).sum();

这很好但我的问题是我需要在汇总之前将其他类型的值设置为defalute值0,类似于

   List<double> ActualLength = new List<double>();

   if( n.TripPath.DataType =="type1" || n.tripPath.DataType == "Type2")
       ActualLength.Add(n.trippath.length)
   else
       ActualLength.Add(0);

   return ActualLength.sum();

2 个答案:

答案 0 :(得分:0)

如果我理解正确,你需要这样的东西:

var projection =
    tmp.SelectMany(x => x)
       .Select(x => {
           if(x.TripPath.DataType == "type1" || x.TripPath.DataType == "type2") {
               return new { Item = x, Length = x.TripPath.Length };
           }
           else {
               return new { Item = x, Length = 0 };
           }
       });

然后你可以说

int length = projection.Sum(x => x.Length);

这就是你可以完成你想要做的事情的方法(将每个与谓词匹配的项目投影到它的长度,然后将其投影到零)。

但是,您的使用看起来甚至没有使用投影。在这种情况下,你可以逃脱

return tmp.SelectMany(x => x)
          .Where(x => 
              x.TripPath.DataType == "type1" ||
              x.TripPath.DataType == "type2"
          )
          .Sum(x => x.TripPath.Length);

与谓词不匹配的项目不会达到总和的序列,因此它们不会对总和做出任何贡献。

答案 1 :(得分:-1)

看一下OfType扩展方法。然后,您可以投射到匿名类型以指定默认值,并将.Sum指定为此。

相关问题