Helper function that swaps erasing element with the back element and then erases the back. - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IList

Description

Helper function that swaps erasing element with the back element and then erases the back.

Demo Code


using System.Collections.Generic;

public class Main{
        /// <summary>
        /// Helper function that swaps erasing element with the back element and then erases the back.
        /// </summary>
        /// <remarks>
        /// This function helps avoid array rearrangements but is only useful for collections where element order does not matter.
        /// </remarks>
        /// <typeparam name="T">List element type.</typeparam>
        /// <param name="i_List">List container.</param>
        /// <param name="i_Element">Element to erase.</param>
        public static void RemoveSwap<T>(this IList<T> i_List, T i_Element)
        {//  ww  w . ja va  2 s  . c o  m
            Log.DebugAssert(i_List != null, "Invalid null parameter.");

            int size = i_List.Count;
            if (size > 0)
            {
                int index = i_List.IndexOf(i_Element);
                if (index >= 0)
                {
                    int lastIndex = size - 1;
                    T temp = i_List[lastIndex];
                    i_List.RemoveAt(lastIndex);
                    i_List[index] = temp;
                }
            }
        }
        /// <summary>
        /// Helper function that swaps erasing element with the back element and then erases the back.
        /// </summary>
        /// <remarks>
        /// This function helps avoid array rearrangements but is only useful for collections where element order does not matter.
        /// </remarks>
        /// <typeparam name="T">List element type.</typeparam>
        /// <param name="i_List">List container.</param>
        /// <param name="i_Index">Index of element to erase.</param>
        public static void RemoveSwap<T>(this IList<T> i_List, int i_Index)
        {
            Log.DebugAssert(i_Index >= 0 && i_Index < i_List.Count, "CollectionExtensions.RemoveSwap Index out of bounds.");

            int size = i_List.Count;
            if (size > 0)
            {
                int lastIndex = size - 1;
                T temp = i_List[lastIndex];
                i_List.RemoveAt(lastIndex);
                i_List[i_Index] = temp;
            }
        }
}

Related Tutorials