Returns a value Indicating whether an item can be inserted in a collection. - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:ICollection

Description

Returns a value Indicating whether an item can be inserted in a 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   ww w.j a v  a 2 s  . c  o  m

public class Main{
        /// <summary>
        /// Returns a value Indicating whether an item can be inserted in a 
        /// collection.
        /// </summary>
        /// <param name="collection">The collection.</param>
        /// <param name="item">The item to be inserted.</param>
        /// <returns>A value Indicating whether an item can be inserted in a 
        /// collection.</returns>
        public static bool CanInsert(this IEnumerable collection, object item)
        {
            ICollectionView collectionView = collection as ICollectionView;
            if (collectionView != null)
            {
                return CanInsert(collectionView.SourceCollection, item);
            }

            if (IsReadOnly(collection))
            {
                return false;
            }

            Type genericListType = collection.GetType().GetInterfaces().Where(interfaceType => interfaceType.FullName.StartsWith("System.Collections.Generic.IList`1", StringComparison.Ordinal)).FirstOrDefault();
            if (genericListType != null)
            {
                return genericListType.GetGenericArguments()[0] == item.GetType();
            }

            if (collection is IList)
            {
                return true;
            }
            return false;
        }
}

Related Tutorials