Find if a Collection (IEnumerable) has any Item

If a Method or Property returns IEnumerable or Inumerable<T> Types, the only thing that is inherently possible on them is to Loop through (foreach{}). Sometimes it helps to know if the Collection has any items, without having to initiate a loop. The IEnumerable Interface is bare minimum for a collection and does not expose any properties at all. LINQ provides a convenient Extension Method called Any(), that you can call on any IEnumerable Type. Internally, this Method checks if any item is available in the Collection using the following code:

If you do not have LINQ in the project, or want a shortcut of this without having to call the Any() method, here is an alternative:

However, if we know the underlying Type of the Collection also implements ICollection Interface, we can simply cast it to ICollection and check the Count Property:

bool hasItems = ((ICollection)products).Count > 0;

The Count Property is maintained very efficiently by the Framework Collection classes. It would be preferable than having to call any Method.

Combining these two approach, here is another Extension Method that can be used for the same purpose:

//An alternate to the IEnumerable.Any() Method
public static bool HasItem(this IEnumerable source)
{
    if (source == null)
    {
        throw new ArgumentNullException("source");
    }
    if( source is ICollection)
        return ((ICollection)source).Count > 0;
    else
        return source.GetEnumerator().MoveNext();
}

Ideally, an IEnumerator should be wrapped within a using{...} block, like it is shown in the Framework's implementation of Any() Method above. Also note that there is an overload of the IEnumerable.Any() Method. It takes a Func<TSource, bool> and returns true only if any of the Collection items match the given condition. Here is an example:

//Lets assume there is a variable called products, with a collection of Product objects
//Product object has a boolean property called OnBackOrder
//We want to find out if any of the products is on back order
bool IsAnyOnBackorder = products.Any(p => p.OnBackOrder);
Posted on January 8, 2010 09:51 by Haider

Don't Post SPAM

If you are posting a commment just to get a link, don't waste your time!

I have a sophisticated comment moderation system in place, and your comment will not be posted.

Add comment




biuquote
  • Comment
  • Preview
Loading