空流上的Observable.Min / Max抛出异常? [英] Observable.Min/Max throw Exception on Empty Stream?
问题描述
如果在运行min / max时流为空,是否会引发异常?
Is the expected behavior to throw an exception if the stream is empty when running min/max?
除了使用minBy / maxBy之外,我如何测试以确保存在值如果序列有可能为空,则在热流上运行min / max?
Other than using minBy/maxBy how can I test to ensure values exists and run min/max on a hot stream if there is potential for the sequence to be empty?
推荐答案
你还希望看到什么?当你得到一个空序列。国际海事组织你正在采取一组许多并将其减少到一组1.如果该组是空的,单个值是什么?
What are you hoping to see when you get an empty sequence. IMO you are taking a set of many and reducing it to a set of 1. If the set is empty, what would the single value be?
如果你有答案那么甜!
我能想到的2个选项是:
2 options I can think of are:
1)如果源序列为空,则输出序列应为空
1) If the source sequence is empty, then the output sequence should be empty
var source = Observable.Empty<int>();
//source.Min() causes OnError(InvalidOperationEx)
//Empty sequence with MinBy
source.MinBy(x=>x)....
//Empty sequence with Catch/Swallow
source.Min()
.Catch((InvalidOperationException ex)=>Observable.Empty<int>())
2)如果为空(0,null等等),则返回默认的最小值
2) Return a default min value if empty (0, null, etc...)
var defaultValue = 0;
var source = Observable.Empty<int>();
//source.Min().Dump("min");//OnError(InvalidOperationEx)
//Catch error and continue with default value.
source.Min()
.Catch((InvalidOperationException ex)=>Observable.Return<int>(defaultValue))
.Dump("catch");
所以是的,MinBy做出与Min不同的事情有点奇怪。但是这里有一些选择。
So yeah, it is a bit weird that MinBy does something different to Min. But here are some options for you.
Lee
这篇关于空流上的Observable.Min / Max抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!