Blog Stats
  • Posts - 18
  • Articles - 0
  • Comments - 583
  • Trackbacks - 69

 

Converting System.Collections to System.Collections.Generic

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

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Feedback

# re: Converting System.Collections to System.Collections.Generic

Gravatar Thanks! That's exactly why I post my ideas...so I can hear about better ideas. ;)

Billy 7/11/2006 7:43 AM | Billy

# re: Converting System.Collections to System.Collections.Generic

Gravatar I've been using http://www.codeproject.com/dotnet/dynamiclistsorting.asp for sorting all my generics...very useful utility.

Billy 7/11/2006 11:15 AM | Billy

# re: Converting System.Collections to System.Collections.Generic

Gravatar How would you convert the following to vb:


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

4/10/2007 8:03 AM | newbee

# re: Converting System.Collections to System.Collections.Generic

Gravatar Since I have hardly any experience with VB.NET, I won't be able to provide an answer to this myself. 4/10/2007 8:09 AM | Billy McCafferty

# This is my first time i visit here. I discovered so numerous interesting stuff in your weblog especially its discussion. From th

Gravatar interesting post, pretty much covered it all for me, thank you 3/30/2011 2:41 AM | Windows 7 Key

Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

 

 

Copyright © Billy McCafferty