SingleOrDefault()在多个元素上引发异常 [英] SingleOrDefault() throws an exception on more than one element
问题描述
每次获取这样的内容都会得到一个例外
I'm getting an exception whenever I fetch like this
Feature f = o.Features.SingleOrDefault(e => e.LinkName == PageLink);
因为它可以返回一个或多个元素.我可以用来解决此问题的替代方法是什么?
because this can return one or more than one element. What is the alternative approach that I can use to solve this issue?
推荐答案
Single和SingleOrDefault用于在序列中存在多个匹配项时抛出.这样的结果是必须在完成之前迭代整个序列.听起来这不是您想要的.请尝试使用FirstOrDefault:
Single and SingleOrDefault are designed to throw if more that one match exists in the sequence. A consequence of this is that the entire sequence must be iterated prior to completion. It does not sound like this is what you want. Try FirstOrDefault instead:
Feature f = o.Features
.FirstOrDefault(e => e.vcr_LinkName == PageLink && e.bit_Activate == true);
(通常)它会更好地执行,因为一旦找到匹配项,它就会完成.
This will (generally) perform better because it completes as soon as a match is found.
当然,如果您实际上想保留多个元素,那么Where子句会更合适:
Of course, if you actually want to retain more than one element, a Where clause would be more appropriate:
IEnumerable<Feature> fs = o.Features
.Where(e => e.vcr_LinkName == PageLink && e.bit_Activate == true);
这篇关于SingleOrDefault()在多个元素上引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!