Archive for Maggio 29th, 2008

List To Generic List Converter

CodeKeep C# Feed Maggio 29th, 2008

Description: Converts a non-typed collection into a strongly typed collection
Credits: http://weblogs.asp.net/bsimser/archive/2007/05/08/generic-list-converter-snippet.aspx

Link: http://www.codekeep.net/snippets/f3658f93-d7c7-44c0-8431-6a826a2678ba.aspx

/// <summary>
         /// Converts a non-typed collection into a strongly typed collection.  This will fail if
         /// the non-typed collection contains anything that cannot be casted to type of T.
         /// </summary>
         /// <param name="listOfObjects">A <see cref="ICollection"/> of objects that will
         /// be converted to a strongly typed collection.</param>
         /// <returns>Always returns a valid collection - never returns null.</returns>

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