diff --git a/ICD.Common.Utils.Tests/Extensions/EnumerableExtensionsTest.cs b/ICD.Common.Utils.Tests/Extensions/EnumerableExtensionsTest.cs index ef0a621..6cf3a7d 100644 --- a/ICD.Common.Utils.Tests/Extensions/EnumerableExtensionsTest.cs +++ b/ICD.Common.Utils.Tests/Extensions/EnumerableExtensionsTest.cs @@ -288,6 +288,24 @@ namespace ICD.Common.Utils.Tests.Extensions Assert.AreEqual(3, values[1]); } + [Test] + public void ToArrayCountTest() + { + int[] array = Enumerable.Range(0, 100).ToArray(); + int[] copy = array.ToArray(array.Length); + + Assert.IsTrue(copy.SequenceEqual(array)); + } + + [Test] + public void ToListCountTest() + { + List array = Enumerable.Range(0, 100).ToList(); + List copy = array.ToList(array.Count); + + Assert.IsTrue(copy.SequenceEqual(array)); + } + [Test] public void ToHashSetTest() { diff --git a/ICD.Common.Utils/Extensions/EnumerableExtensions.cs b/ICD.Common.Utils/Extensions/EnumerableExtensions.cs index 02ec582..24498ed 100644 --- a/ICD.Common.Utils/Extensions/EnumerableExtensions.cs +++ b/ICD.Common.Utils/Extensions/EnumerableExtensions.cs @@ -504,6 +504,49 @@ namespace ICD.Common.Utils.Extensions return new IcdHashSet(extends); } + /// + /// Optimized ToArray implementation with fewer allocations. + /// + /// + /// + /// + /// + public static T[] ToArray(this IEnumerable extends, int count) + { + if (extends == null) + throw new ArgumentNullException("extends"); + + if (count < 0) + throw new ArgumentOutOfRangeException("count"); + + T[] array = new T[count]; + int i = 0; + + foreach (T item in extends) + array[i++] = item; + return array; + } + + /// + /// Optimized ToList implementation with fewer allocations. + /// + /// + /// + /// + /// + public static List ToList(this IEnumerable extends, int count) + { + if (extends == null) + throw new ArgumentNullException("extends"); + + if (count < 0) + throw new ArgumentOutOfRangeException("count"); + + List list = new List(count); + list.AddRange(extends); + return list; + } + /// /// Returns the sequence as an index:value dictionary. ///