Blog Stats
  • Posts - 18
  • Articles - 0
  • Comments - 42
  • Trackbacks - 76

 

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


Feedback

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

Gravatar Hi Billy, I use the Power Collections at www.wintellect.com. There is a method in the Algorithms utilitiy called TypedAs<T> that does this conversion and is very fast...so in your NHibernate library you'd have:
return Algorithms.TypedAs<T>(criteria.List());


There are a huge number of other very useful functions this library has (open source too!).

Hope this helps 7/11/2006 4:42 AM | Mike

# 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 The collections are great...just be careful using the Sort methods they provide on the NHibernate.Generics collections...messing with the internals of those collections has caused me problems in the past and I haven't debugged completely to see why. 7/11/2006 11:08 AM | Mike

# 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

Post a comment





 

 

 

Copyright © Billy McCafferty