Remove an item by swapping it with the last item and removing it from the last position. - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IList

Description

Remove an item by swapping it with the last item and removing it from the last position.

Demo Code


using System.Collections.Generic;
using System;//from   w w w  .  ja  v  a2 s.  c  o  m

public class Main{
        /// <summary>
        /// Remove an item by swapping it with the last item and removing it from the last position. This function prevents to shift values from the list on removal but does not maintain order.
        /// </summary>
        /// <param name="list">The list.</param>
        /// <param name="item">The item to remove.</param>
        public static void SwapRemove<T>(this IList<T> list, T item)
        {
            int index = list.IndexOf(item);
            if (index < 0)
                return;

            list.SwapRemoveAt(index);
        }
        /// <summary>
        /// Remove an item by swapping it with the last item and removing it from the last position. This function prevents to shift values from the list on removal but does not maintain order.
        /// </summary>
        /// <param name="list">The list.</param>
        /// <param name="index">Index of the item to remove.</param>
        public static void SwapRemoveAt<T>(this IList<T> list, int index)
        {
            if (index < 0 || index >= list.Count) throw new ArgumentOutOfRangeException("index");

            if (index < list.Count - 1)
            {
                list[index] = list[list.Count - 1];
            }

            list.RemoveAt(list.Count - 1);
        }
}

Related Tutorials