Generic List Converter Snippet

A useful little class that you might find you need someday. It converts a weakly-typed list (like an IList of items) into a strongly typed one based on the type you feed it.

It's super simple to use. For example let's say you get back an IList<People> from some service (a data service, web service, etc.) but really need it to be a List<People>. You can just use this class to convert it for you.

I know, silly little example but just something for your code snippets that you can squirrel away for a rainy day.

    1 public class ListToGenericListConverter<T>

    2 {

    3     /// <summary>

    4     /// Converts a non-typed collection into a strongly typed collection.  This will fail if

    5     /// the non-typed collection contains anything that cannot be casted to type of T.

    6     /// </summary>

    7     /// <param name="listOfObjects">A <see cref="ICollection"/> of objects that will

    8     /// be converted to a strongly typed collection.</param>

    9     /// <returns>Always returns a valid collection - never returns null.</returns>

   10     public List<T> ConvertToGenericList(IList listOfObjects)

   11     {

   12         ArrayList notStronglyTypedList = new ArrayList(listOfObjects);

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

   14     }

   15 }

8 Comments

  • FWIW, I think this will result in copying the elements three times. ;) From listOfObjects to notStronglyTypedList, to a temporary array to the typed list that gets returned. Alternative version:

    List Conv...(IList listOfObjects) {
    List items = new List();
    foreach (T obj in listOfObjects) {
    items.Add(obj);
    }
    return items;
    }

  • Can always use AddRange()...

  • I take it by IList you mean "an IList containing People objects".

  • A major benefit of Wilco's approach is that you can accept an IEnumerable instead of an IList, which makes it much more generally useful.

  • I also have an alternative which will twice.
    List Conv...(IList listOfObjects) {
    T[] temp = new T[ listOfObjects.Count ];

    listOfObjects.CopyTo( temp, 0 );

    return new List( temp );
    }

  • @Scott: Yes, looking at it now I see it is. It was something in our codebase around NHibernate which I thought was useful but yes, it came from that article. Although its interesting now to see the alternatives. Might be interesting to compare and see what's the most efficient.

  • Let the bearded great white wizard speak, if anything it's Billy McCafferty that's the repulsive slug.

  • Hi,

    I have a generic list like HashSet in my business layer, and I have the same HashSet in my data access layer, when 'am assigning the HashSet obj with HashSet this obj, it is throwing the exception as mismatch. Is there any solution for this to type cast or translate the objects.

    Thanks in advance

Comments have been disabled for this content.