I needed an array of strings for the string.Join() method. I put together a quick ToArray<T>() extension method which iterated through each item in the array and created an array T[]. The problem is, if I already have an array, that's a lot of extra work and some wasted memory.
So, I tried IList<T> is Array and it works great. I just cast the IList<T> as T[] and return it. Otherwise, I execute the iteration. Here's what it looks like:
public static T[] ToArray<T>(this IList<T> list)Pretty basic, but nice n' fast.
{
if (list is Array) return (T[]) list;
T[] retval = new T[list.Count];
for (int i = 0; i < retval.Length; i++)
retval[i] = list[i];
return retval;
}
System.Linq.Enumerable has the same extension method now
ReplyDeleteGreat method. I'm working on code that is restricted to .NET 2.0 and therefore can't access the System.Linq version of a similar method.
ReplyDelete