Gets the number of items in the collection. - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:ICollection

Description

Gets the number of items in the collection.

Demo Code

// (c) Copyright Microsoft Corporation.
using System.Reflection;
using System.Linq;
using System.Diagnostics.CodeAnalysis;
using System.ComponentModel;
using System.Collections;
using System;/*from  w  w  w.j  a v  a 2  s .  c  o m*/

public class Main{
        /// <summary>
        /// Gets the number of items in the collection.
        /// </summary>
        /// <param name="collection">The collection.</param>
        /// <returns>The number of items in the collection.</returns>
        public static int Count(this IEnumerable collection)
        {
            ICollectionView collectionView = collection as ICollectionView;
            if (collectionView != null)
            {
                return collectionView.SourceCollection.Count();
            }
            else
            {
                Type genericListType = collection.GetType().GetInterfaces().Where(interfaceType => interfaceType.FullName.StartsWith("System.Collections.Generic.ICollection`1", StringComparison.Ordinal)).FirstOrDefault();
                if (genericListType != null)
                {
                    return (int) genericListType.GetProperty("Count").GetValue(collection, new object[] { });
                }

                IList list = collection as IList;
                if (list != null)
                {
                    return list.Count;
                }
                
                return System.Linq.Enumerable.Count(collection.OfType<object>());
            }
        }
}

Related Tutorials