简体   繁体   中英

How to check if a Stack<T> is empty

Is there some other way, except Stack<T>.Count() == 0 , to check if a Stack<T> is empty?

Coming from C++/Java background where "stack" classes generally have some sort of dedicated "is empty" method like Java - Stack.empty .

Instead of using .Count() == 0 , just use .Count == 0 . This is using the stack's property rather than the linq extension method.

There are three common approaches, and which one you use will usually be a matter of taste.

if(!stack.Any()) ...
if(stack.Count() == 0) ...
if(stack.Count == 0) ...

Profiling the different approaches looks like this :

基准测试

.Any() and .Count() take 10x-20x longer than .Count ... and can still run tens of thousands of times per millisecond . So .Count > 0 is "much faster", but the others are still fast enough to not have to worry about under most circumstances. I'd personally stick with Any() since I feel it reads better, but I wouldn't give anyone flak for choosing Count .

You can create your own extension method too

namespace System.Collection.Generic {
   public static class SystemEx {
        public static bool IsEmpty<T>(this Stack<T> stack) {
            return (stack.Count==0);
        }    
   }

You can use stack.Any() . Fast, readable, and standard way for all IEnumerable<T> objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM