Geeks With Blogs
Billy McCafferty whatever (but really just .NET)

I believe the following is the fastest way to convert a non-typed list to a strongly typed (generic) list using C# .NET:

public List ConvertToGenericList(IList listOfObjects) {
   ArrayList notStronglyTypedList = new ArrayList(listOfObjects);
   return new List(notStronglyTypedList.ToArray(typeof(T)) as T[]);
}

Note that this will fail if the non-typed collection contains anything that cannot be casted to type of T.

Please let me know if there's a more efficient way to do this!

Billy

Posted on Monday, July 10, 2006 1:55 PM C# | Back to top


Comments on this post: Converting System.Collections to System.Collections.Generic

# re: Converting System.Collections to System.Collections.Generic
Requesting Gravatar...
Thanks! That's exactly why I post my ideas...so I can hear about better ideas. ;)

Billy
Left by Billy on Jul 11, 2006 7:43 AM

# re: Converting System.Collections to System.Collections.Generic
Requesting Gravatar...
I've been using http://www.codeproject.com/dotnet/dynamiclistsorting.asp for sorting all my generics...very useful utility.

Billy
Left by Billy on Jul 11, 2006 11:15 AM

# re: Converting System.Collections to System.Collections.Generic
Requesting Gravatar...
How would you convert the following to vb:


return new List(notStronglyTypedList.ToArray(typeof(T)) as T[]);

Left by newbee on Apr 10, 2007 8:03 AM

# re: Converting System.Collections to System.Collections.Generic
Requesting Gravatar...
Since I have hardly any experience with VB.NET, I won't be able to provide an answer to this myself.
Left by Billy McCafferty on Apr 10, 2007 8:09 AM

# This is my first time i visit here. I discovered so numerous interesting stuff in your weblog especially its discussion. From th
Requesting Gravatar...
interesting post, pretty much covered it all for me, thank you
Left by Windows 7 Key on Mar 30, 2011 2:41 AM

Your comment:
 (will show your gravatar)


Copyright © Billy McCafferty | Powered by: GeeksWithBlogs.net