我应该使用单()或的SingleOrDefault(),如果有机会的元素不会被发现?有机会、元素、发现、SingleOrDefault

2023-09-02 10:55:26 作者:离岛茶霏=

请问您preFER看?

What would you prefer to see?

try
{
  var item = list.Single(x => x.HasFoo);
}
catch(InvalidOperationException e)
{
  throw new InvalidOperationException("Exactly one item with foo expected, none found", e);
}

或者

var item = list.SingleOrDefault(x => x.HasFoo);
if (item == null)
      throw new InvalidOperationException("Exactly one item with foo expected, none found");

什么是最好的做法吗?哪一个做的异常的详细COM prehensible?

What's the best practice here? Which one makes the exception more comprehensible?

推荐答案

使用的SingleOrDefault()如果0或1资料的预期 使用单()如果为1,而不是0或2个及以上,项目预计

Use SingleOrDefault() if 0 or 1 items are expected Use Single() if 1, not 0 or 2 and more, item is expected

另外请记住,有一些可能出现的情况:

Also keep in mind that there are a number of possible scenarios:

您得到0时0或1预期(OK) 您有1时0或1预期(OK) 您有2个或更多时0或1,预计(错误)

您得到0时1预计(错误) 您有1 1时预期(OK) 您有2个或以上时,1预计(错误)

和不要忘了一() FirstOrDefault()任何()