为什么发现多个元素时Single()不直接返回? [英] Why does Single() not return directly when more than one element is found?

查看:91
本文介绍了为什么发现多个元素时Single()不直接返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(大约)我在 Enumerable.Single 方法,同时使用一些反编译器进行检查:

I found (roughly) this code in the Enumerable.Single method while inspecting it with some decompiler:

foreach (TSource current in source)
{
    if (predicate(current))
    {
        result = current;
        num += 1L;
    }
}

if (num > 1L)
{
     throw Error.MoreThanOneMatch();
}

如您所见,它会在抛出之前循环遍历所有项目.为什么在num > 1时它不中断?

As you can see, it loops over all items before throwing. Why doesn't it break when num > 1?

推荐答案

同意,从性能的角度来看会更好(如果我们期望有多个与谓词匹配的项目,我们不应该这样做):

Agree, that it will be better from terms of performance ( if we are expecting more than one item matching our predicate, which we should not do):

foreach (TSource current in source)
{
    if (predicate(current))
    {
        result = current;
        num += 1L;

        if (num > 1L)
            throw Error.MoreThanOneMatch();
    }
}

if (num == 0L)
   throw Error.NoMatch();

return local;

看起来他们决定使结果分析更加清晰,并将其与枚举源分开.但是然后我想知道为什么不使用简单的开关:

Looks like they decided to make results analyzing more clear and separated it from enumerating source. But then I wonder why simple switch was not used:

switch((int)num)
{
   case 0: throw Error.NoMatch();
   case 1: return local;
   default:
       throw Error.MoreThanOneMatch();    
}

关于性能问题-我认为,当您真正期望单个结果时,应该调用Single.零个或多个结果是一个例外路径,该路径不应经常发生(任何例外情况).因此,如果源包含许多与谓词匹配的项目,则更可能是程序的逻辑错误.

Regarding to performance issues - I think it's assumed that Single should be called when you are really expecting single result. Zero or more results is an exceptional path, which should not occur often (as any exception). So, it's more your program's logic error if source contain many items matching predicate.

这篇关于为什么发现多个元素时Single()不直接返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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