我可能只是在最接近的使用点捕捉异常。
这是因为LastOrDefault/FirstOrDefault
超过一个IEnumerable<int>
将返回0(对于int
默认值),其可以是一个“有效”值 - 这取决于实际的上下文和定义的规则。虽然将序列转换为IEnumerable<int?>
将允许以前的方法返回null
,这似乎是更多的工作,而不是价值。
如果需要对一个继续使用使用lastScore
,考虑:
int? lastScore; /* Using a Nullable<int> to be able to detect "not found" */
try {
lastScore = list.Last(x => x < 100); /* int -> int? OK */
} catch (InvalidOperationException) {
lastScore = null; /* If 0 see LastOrDefault as suggested;
otherwise react appropriately with a sentinel/flag/etc */
}
if (lastScore.HasValue) {
/* Found value meeting conditions */
}
或者,如果能够抛弃时没有找到的情况下,可以考虑:
try {
var lastScore = list.Last(x => x < 100);
/* Do something small/immediate that won't throw
an InvalidOperationException, or wrap it in it's own catch */
return lastScore * bonus;
} catch (InvalidOperationException) {
/* Do something else entirely, lastScore is never available */
return -1;
}
欢迎SO!说了这些,我很困惑你的问题。 'List'不能是'list'的类型,因为'int'当然没有'Score'属性。请澄清。 –
J0e3gan
2014-09-13 05:07:39
真的很抱歉!我打算写'list.Last(x => x <100)'。感谢您指出它。我也编辑了这个问题。 – 2014-09-13 05:11:49