我正在try 实现一个函数,它过滤掉一些条目,并取由具体函数映射的最小值,然后要么返回由它判断的最小值,要么在过滤掉所有元素后得到null
:
public readonly record struct PdfVerticalPos(float Raw_LessIsBelow)
{
}
public readonly record struct AxisAlignedRenderingBox
{
public AxisAlignedRenderingBox(PdfVerticalPos upMost, PdfVerticalPos downMost, float leftMostRaw, float rightMostRaw)
{
this.UpMost = upMost;
this.DownMost = downMost;
this.LeftMost = leftMostRaw;
this.RightMost = rightMostRaw;
}
}
private static string? findTheBottomByCondition(IEnumerable<(AxisAlignedRenderingBox, string)> detectedStrings,
float leftMostMin, float leftMostMax, Func<(AxisAlignedRenderingBox, string), bool> selectingPredicate)
{
return detectedStrings
.Where(selectingPredicate)
.Where(tuple => leftMostMin <= tuple.Item1.LeftMost && tuple.Item1.LeftMost <= leftMostMax)
.MinBy(tuple => tuple.Item1.UpMost.Raw_LessIsBelow).Item2;
}
internal void someCallSite() {
var detectedStrings = whatever();
var found = findTheBottomByCondition(detectedStrings, 60, 65,
tuple => tuple.Item1.UpMost.Raw_LessIsBelow >= baseY);
// do whatever
}
然而,当呼叫MinBy
时,它会抛出InvalidOperationException
.当我判断原因时,我发现文档上写着"如果TSource
是一个原始类型并且源序列为空,则抛出InvalidOperationException
".不确定"基本类型"是什么意思,因为元组显然不是opposed to integers的基本类型.
因此,我重写了findTheBottomByCondition
条,如下所示:
private static string? findTheBottomByCondition(IEnumerable<(AxisAlignedRenderingBox, string)> detectedStrings,
float leftMostMin, float leftMostMax, Func<(AxisAlignedRenderingBox, string), bool> selectingPredicate) {
var valueTuples = detectedStrings.ToList();
var a = valueTuples
.Where(selectingPredicate)
.Count(tuple => leftMostMin <= tuple.Item1.LeftMost && tuple.Item1.LeftMost <= leftMostMax);
if (a > 0)
{
return valueTuples
.Where(selectingPredicate)
.Where(tuple => leftMostMin <= tuple.Item1.LeftMost && tuple.Item1.LeftMost <= leftMostMax)
.MinBy(tuple => tuple.Item1.UpMost.Raw_LessIsBelow).Item2;
}
else
{
return null;
}
}
虽然它工作正常,但不是很优雅,只是避免了异常.我希望它返回null
,如果没有找到它,不管它是不是"原始类型",你有什么 idea 吗?我想我可以通过catch
-ING InvalidOperationException
来实现它,但我不喜欢这种方式,也不喜欢目前大多数复制粘贴和糟糕的实现.