Removes an item at a given index from the collection. - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:ICollection

Description

Removes an item at a given index from 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.jav  a  2 s  . c  om*/

public class Main{
        /// <summary>
        /// Removes an item at a given index from the collection.
        /// </summary>
        /// <param name="collection">The collection.</param>
        /// <param name="index">The index of the item to be removed.</param>
        [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Code is linked into multiple projects.")]
        public static void RemoveAt(this IEnumerable collection, int index)
        {
            ICollectionView collectionView = collection as ICollectionView;
            if (collectionView != null)
            {
                collectionView.SourceCollection.RemoveAt(index);
            }
            else
            {
                Type genericListType = collection.GetType().GetInterfaces().Where(interfaceType => interfaceType.FullName.StartsWith("System.Collections.Generic.IList`1", StringComparison.Ordinal)).FirstOrDefault();
                if (genericListType != null)
                {
                    genericListType.GetMethod("RemoveAt").Invoke(collection, new object[] { index });
                }
                else
                {
                    IList list = collection as IList;
                    list.RemoveAt(index);
                }
            }
        }
}

Related Tutorials