Skip to content

Instantly share code, notes, and snippets.

@kcargile
Created September 21, 2012 16:20
Show Gist options
  • Save kcargile/3762437 to your computer and use it in GitHub Desktop.
Save kcargile/3762437 to your computer and use it in GitHub Desktop.
.NET Clones a collection into an array of the specified type.
namespace Extensions
{
/// <summary>
/// Extension methods for classes that implement the <see cref="IEnumerable"/> interface.
/// </summary>
public static class IEnumerableExtensions
{
/// <summary>
/// Converts the collection to an array that is a deep copy of the source list.
/// </summary>
/// <typeparam name="TU">The type of the U.</typeparam>
/// <param name="source">The source.</param>
/// <returns>An array of the specified type.</returns>
public static TU[] ToClonedArray<TU>(this IEnumerable<TU> source) where TU : ICloneable
{
int ct = source.Count();
IList<TU> sourceList = source.ToList();
TU[] final = new TU[ct];
for (int i = 0; i < ct; i++)
{
final[i] = (TU)sourceList[i].Clone();
}
return final;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment