相关疑难解决方法(0)

如果有可能找不到元素,我应该使用Single()还是SingleOrDefault()?

你更喜欢看什么?

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

要么:

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

这里的最佳做法是什么?哪一个让异常更容易理解?

.net c# linq coding-style

35
推荐指数
2
解决办法
3万
查看次数

标签 统计

.net ×1

c# ×1

coding-style ×1

linq ×1