About Me

My photo
Kozyatağı, İstanbul, Türkiye
Showing posts with label IEnumerable. Show all posts
Showing posts with label IEnumerable. Show all posts

Sunday, March 10, 2013

Efficient Way of Determining Whether a Collection Contains Element / Is Non-Empty


Determining “whether a collection is non-empty” is considered as one of the most basic and simple algorithms and generally coded as:


return collection.TakeCount() > 0;

               
For collections that can grow dynamically i.e. List, Dictionary, etc. such a code can be very costly in some circumstances.

If you’re using property of ICollection class, there is no problem. You can safely continue use them for framework collection classes since it keeps the count pre-calculated.

If you are using function of IEnumarable interface,  take a little notice. Because implementation of function over the .NET Framework collection classes calculate the count by iterating through all elements in the collection.

For collections that contain thousands or millions of element, that cost is highly redundant for such a simple “Is Non-Empty?” operation.

The code below determines “if the collection is non-empty” without counting and very quickly:

C# Code:
        static bool ContainsElement(IEnumerable coll)
        {
            if (coll == null)
            {
                return false;
            }

            foreach (var item in coll)
            {
                return true;
            }
            return false;
        }

A shortcut for IEnumerable<T> classes can be:

C# Code:
       static bool ContainsElement<T>(IEnumerable<T> coll)
        {
            return coll != null && coll.Any();
        }