如何处理 LINQ 查询没有返回结果的情况?
以下 LINQ 查询工作正常,除非没有结果可返回。然后抛出 InvalidOperationException。
处理这个问题的最佳方法是什么?如何测试结果是否存在并在没有结果的情况下继续前进?我考虑过尝试捕获,但觉得必须有一个更优雅的解决方案。
在此示例中,我只期望第一个结果的 ID。可能还有其他情况我希望返回整个对象。
var drId = dcDest.drs.Where(dr => dr.ContactID == contactId)
.Select(dr => dr.Id).First();
int xId = drId;
The following LINQ query works fine except when there are no results to return. Then an InvalidOperationException is thrown.
What is the best way to handle this? How do I test for the existance of a result and move along if there is none? I thought about a try-catch but felt there must be a more elegant solution.
In this example, I'm only expecting the Id of the first result. There may be other case where I want the entire object returned.
var drId = dcDest.drs.Where(dr => dr.ContactID == contactId)
.Select(dr => dr.Id).First();
int xId = drId;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该使用
SingleOrDefault()
。FirstOrDefault() 也可以工作,但实际上你是说集合中应该只有一个,这使得 'SingleOrDefault()' 成为更合适的选择(如果有多个,它会抛出异常)。
另一方面,如果您期望一个序列,但需要处理没有返回元素的情况,您也可以使用
DefaultIfEmpty()
在序列为空时返回默认值。请参阅 http://msdn.microsoft.com/en-us/library/bb355419。 aspx当它为空时你想要什么行为? id 为零还是其他什么?
You should use
SingleOrDefault()
.FirstOrDefault()
could work too but really you are saying that there should only be one in the collection which makes 'SingleOrDefault()' the more proper choice (it will throw an exception if there is more than one).If on the other hand you are expecting a sequence but need to handle the case when no elements are returned you can also use
DefaultIfEmpty()
to return a default value when the sequence is empty. See http://msdn.microsoft.com/en-us/library/bb355419.aspxWhat behavior do you want when it is empty? An id of Zero or something else?