using System; using System.Collections.Generic; namespace Unity.Collections { /// /// Extension methods for lists. /// public static class ListExtensions { /// /// Finds and removes the first occurrence of a particular value in the list. /// /// /// If found, the first occurrence of the value is overwritten by the last element of the list, and the list's length is decremented by one. /// /// The type of elements in the list. /// The list to search. /// The value to locate and remove. /// Returns true if an element was removed. public static bool RemoveSwapBack(this List list, T value) { int index = list.IndexOf(value); if (index < 0) return false; RemoveAtSwapBack(list, index); return true; } /// /// Finds and removes the first value which satisfies a predicate. /// /// /// The first value satisfying the predicate is overwritten by the last element of the list, and the list's length is decremented by one. /// /// The type of elements in the list. /// The list to search. /// The predicate for testing the elements of the list. /// Returns true if an element was removed. public static bool RemoveSwapBack(this List list, Predicate matcher) { int index = list.FindIndex(matcher); if (index < 0) return false; RemoveAtSwapBack(list, index); return true; } /// /// Removes the value at an index. /// /// /// The value at the index is overwritten by the last element of the list, and the list's length is decremented by one. /// /// The type of elements in the list. /// The list to search. /// The index at which to remove an element from the list. public static void RemoveAtSwapBack(this List list, int index) { int lastIndex = list.Count - 1; list[index] = list[lastIndex]; list.RemoveAt(lastIndex); } /// /// Returns a copy of this list. /// /// The type of elements in the list. /// The list to copy. /// The allocator to use. /// A copy of this list. public static NativeList ToNativeList(this List list, AllocatorManager.AllocatorHandle allocator) where T : unmanaged { var container = new NativeList(list.Count, allocator); for (int i = 0; i < list.Count; i++) { container.AddNoResize(list[i]); } return container; } /// /// Returns an array that is a copy of this list. /// /// The type of elements in the list. /// The list to copy. /// The allocator to use. /// An array that is a copy of this list. public unsafe static NativeArray ToNativeArray(this List list, AllocatorManager.AllocatorHandle allocator) where T : unmanaged { var container = CollectionHelper.CreateNativeArray(list.Count, allocator, NativeArrayOptions.UninitializedMemory); for (int i = 0; i < list.Count; i++) { container[i] = list[i]; } return container; } } }