C# 6.0 引入了空条件运算符,大获全胜。
现在我想要一个行为类似于它的运算符,但用于空集合。
Region smallestFittingFreeRegion = FreeRegions
.Where(region => region.Rect.W >= width && region.Rect.H >= height)
.MinBy(region => (region.Rect.W - width) * (region.Rect.H - height));
现在如果Where返回一个空IEnumerable,这会爆炸,因为如果集合为空, MinBy(from MoreLinq) 会引发异常。
在 C# 6.0 之前,这可能会通过添加另一个扩展方法 MinByOrDefault来解决。
我想像这样重写它:.Where(...)?.MinBy(...). 但这不起作用,因为.Where返回一个空集合而不是null.
现在这可以通过引入.NullIfEmpty()扩展方法来解决IEnumerable。到达.Where(...).NullIfEmpty()?.MinBy()。
最终这似乎很尴尬,因为返回空集合总是比返回null.
有没有其他更优雅的方式来做到这一点?