c# - Recommended way to check if a sequence is empty -
a method returns sequence, ienumerable<t>
, , want check if empty. how recommend doing that? i'm looking both readability , performance.
the first , obvious way check count greater zero:
if(sequence.count() == 0)
has decent readability, terrible performance since has go through whole sequence.
a method use following:
if(!sequence.any())
this doesn't (as far know) have go through whole sequence, readability bit backwards , awkward. (reads lot better if checking sequence not empty though).
another option use first
in try-catch, this:
try { sequence.first(); } catch(invalidoperationexception) { // }
not pretty solution, , slower too, since using exceptions , stuff. prevent using firstordefault
of course, except have big problem if first item in sequence was default value ;)
so, other ways check if sequence empty? 1 use? 1 recommend use?
note: optimal readability put 1 of above snippets in isempty
extension method, still curious since have inside method :p
i use !sequence.any()
, personally.
if really need to, write own extension method:
public static bool isempty<t>(this ienumerable<t> source) { return !source.any(); }
then can write:
if (sequence.isempty())
Comments
Post a Comment