Tuesday, April 7, 2009

ToArray Extension Method Converts IList<T> to T[]

String ArrayI was talking with my coworker James Brechtel today about writing an extension method to join an array of strings together with a delimiter like string.Join() does. I'd prefer string[].Join() because it seems more fluent. I was throwing the IList<string>.Join() method together when I ran into a small snag.

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)
{
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;
}
Pretty basic, but nice n' fast.

2 comments:

  1. System.Linq.Enumerable has the same extension method now

    ReplyDelete
  2. Great 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