用于查询的 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();
这工作正常,但我的问题是我需要在求和之前将其他类型的值设置为默认值 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();
I am working with lambda expression in c#. I am trying to select a value based on type and then the resultant is summed.
var length = (from al in tmp
from n in al
where n.TripPath.DataType =="type1" || n.tripPath.DataType == "Type2"
select n.trippath.length).sum();
this works fine but my issue is i need to set vales for other types to a defalute value 0 before it is summed, similar to
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();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果我理解正确,你想要这样的东西:
那么你可以说
这就是你如何完成你想要做的事情(将与谓词匹配的每个项目投影到其长度,否则将其投影为零)。
但是,您的使用情况看起来甚至没有使用投影。在这种情况下,您可以逃脱与
谓词不匹配的项目不会命中求和的序列,因此它们不会对总和做出任何贡献。
If I understand correctly, you want something like this:
Then you can say
That is how you can accomplish what it seems like you are trying to do (project each item matching a predicate to its length and otherwise project it to zero).
However, your usage looks like you aren't even using the projections. In which case, you can get away with
Items that don't match the predicate don't hit the sequence that is summed over and therefore they don't contribute anything to the sum.
您可以像这样使用三元条件:
You can use ternary condition like that:
看一下 OfType 扩展方法。然后,您可以投影到匿名类型以分配默认值并对其进行求和。
Take a look at the OfType extension method. You can then project into an anonymous type to assign a default value and .Sum off this.