mirror of
https://github.com/ICDSystems/ICD.Common.Utils.git
synced 2026-01-11 19:44:55 +00:00
Optimized ToList and ToArray extension methods
This commit is contained in:
@@ -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<int> array = Enumerable.Range(0, 100).ToList();
|
||||
List<int> copy = array.ToList(array.Count);
|
||||
|
||||
Assert.IsTrue(copy.SequenceEqual(array));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ToHashSetTest()
|
||||
{
|
||||
|
||||
@@ -504,6 +504,49 @@ namespace ICD.Common.Utils.Extensions
|
||||
return new IcdHashSet<T>(extends);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Optimized ToArray implementation with fewer allocations.
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="extends"></param>
|
||||
/// <param name="count"></param>
|
||||
/// <returns></returns>
|
||||
public static T[] ToArray<T>(this IEnumerable<T> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Optimized ToList implementation with fewer allocations.
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="extends"></param>
|
||||
/// <param name="count"></param>
|
||||
/// <returns></returns>
|
||||
public static List<T> ToList<T>(this IEnumerable<T> extends, int count)
|
||||
{
|
||||
if (extends == null)
|
||||
throw new ArgumentNullException("extends");
|
||||
|
||||
if (count < 0)
|
||||
throw new ArgumentOutOfRangeException("count");
|
||||
|
||||
List<T> list = new List<T>(count);
|
||||
list.AddRange(extends);
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the sequence as an index:value dictionary.
|
||||
/// </summary>
|
||||
|
||||
Reference in New Issue
Block a user