Home
Manage Your Code
Snippet: List To Generic List Converter (C#)
Title: List To Generic List Converter Language: C#
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 Views: 193
Author: Nip Nip Date Added: 5/29/2008
Copy Code  
1/// <summary>

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

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

4         /// </summary>

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

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

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

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