c# - Why does Single() not return directly when more than one element is found? -


this question has answer here:

i found (roughly) code in enumerable.single method while inspecting decompiler:

foreach (tsource current in source) {     if (predicate(current))     {         result = current;         num += 1l;     } }  if (num > 1l) {      throw error.morethanonematch(); } 

as can see, loops on items before throwing. why doesn't break when num > 1?

agree, better terms of performance (edit: if expecting more 1 item matching our predicate, 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 decided make results analyzing more clear , separated enumerating source. wonder why simple switch not used:

switch((int)num) {    case 0: throw error.nomatch();    case 1: return local;    default:        throw error.morethanonematch();     } 

regarding performance issues - think it's assumed single should called when really expecting single result. 0 or more results exceptional path, should not occur (as exception). so, it's more program's logic error if source contain many items matching predicate.


Comments