Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/xamarin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 用于根据条件选择不同值的查询的Lambda表达式_C#_Lambda - Fatal编程技术网

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

C# 用于根据条件选择不同值的查询的Lambda表达式,c#,lambda,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(); 这很好,但我的问题是,在

我正在使用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();

请看OfType扩展方法。然后,您可以投影到一个匿名类型中,以指定一个默认值,并对其进行求和。

如果我理解正确,您希望这样:

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

与谓词不匹配的项不会命中求和的序列,因此它们对求和没有任何贡献。

请使用有关的语言或工具标记您的问题。知道C并且正在查看C标记的人都不会知道存在此问题。为什么需要将其设置为0?如果where筛选它们,则它们将从select中排除,而不包括在总和中。这与将其设置为0的效果相同。Pieter是正确的。另外一点是Enumerable.Empty.Sum或类似值为0。这两点使附加过滤器成为冗余的。