我应该使用单()或的SingleOrDefault(),如果有机会的元素不会被发现? [英] Should I use Single() or SingleOrDefault() if there is a chance that the element won't be found?

查看:148
本文介绍了我应该使用单()或的SingleOrDefault(),如果有机会的元素不会被发现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请问您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()任何()

    这篇关于我应该使用单()或的SingleOrDefault(),如果有机会的元素不会被发现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆