How to test for an empty generic.dictionary collection?

53,004

Solution 1

If it's a generic dictionary, you can just check Dictionary.Count. Count will be 0 if it's empty.

However, in your case, reportGraphs looks like it's an IEnumerator<T> - is there a reason your enumerating your collection by hand?

Solution 2

There's a difference between an empty dictionary and null. Calling MoveNext on an empty collection won't result in a NullReferenceException. I guess in your case you could test if reportGraphs != null.

Share:
53,004
DEH
Author by

DEH

Updated on July 09, 2022

Comments

  • DEH
    DEH almost 2 years

    How do I test a generic dictionary object to see whether it is empty? I want to run some code as follows:

    while (reportGraphs.MoveNext())
    {
        reportGraph = (ReportGraph)reportGraphs.Current.Value;
        report.ContainsGraphs = true;
        break;
    }
    

    The reportGraph object is of type System.Collections.Generic.Dictionary When running this code then the reportGraphs dictionary is empty and MoveNext() immediately throws a NullReferenceException. I don't want to put a try-catch around the block if there is a more performant way of handling the empty collection.

    Thanks.