Share via


How to check if Dictionary is empty?

Question

Tuesday, May 26, 2009 1:41 AM

How to check if a generic dictionary is empty?

All replies (4)

Tuesday, May 26, 2009 3:38 AM âś…Answered

Probably I am missing something here, cant you count the element in dicitionary?

 bool isEmpty= (dic.Count == 0);

Arjun Paudel


Tuesday, May 26, 2009 2:42 AM | 1 vote

Here's the code:

bool isEmpty;
using (var dictionaryEnum = dictionary.GetEnumerator())
{
    isEmpty = !dictionaryEnum.MoveNext();
}

Still, this kind of feels like a hack, and there is a reason for it. You shouldn't care if a dictionary is empty or not. Why do you need this? There's probably a better approach.


Keep it Sharp


Tuesday, May 26, 2009 4:46 AM

LOL

You are absolutely right. Since I never used it (as I said above, you rarely need to count your items in a dictionary) and due to the OP's question I assumed that there was no count property.

I'm sorry.Keep it Sharp


Monday, May 9, 2016 10:03 AM | 1 vote

Oh, you might very well need to care.

Example: Asking for dictionary.Values.Min() will throw an exception if dictionary is empty.

And if you can't assume that your dictionary implements Count() in constant time, then this solution should at least be of constant time-complexity. So +1 from me.

(However, this can only be an issue if you use some badly implemented, possibly 3rd party, custom dictionary class that inherits from IDictionary and implements Count in a bad way, such as actually counting the elements. A normal Dictionary knows already how many elements it has.)