Convert IList to List<T>
Follow up with my NHibernate Series today I have another post talking about one of my favorite Util’s method.
This come from my heavy use of NHibernate classes such as DetachedCriteria, IMultiCriteria and I love to call on it .SetResultTransformer method to transform result into strong type; however its .List() method return an IList which doesn’t uncomforted me much because I addicted to generic & strong type object.
public static IList<T> ConvertToListOf<T>(IList iList)
{
IList<T> result = new List<T>();
foreach (T value in iList)
result.Add(value);
return result;
}
With this little method it allow me to work with generic type again and that is sweet ;)
EDIT: hmm, I just discovered something interesting actually I don’t really need this at all I can just manipulate iList element through foreach().
namespace ConsoleApplication1
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
internal class Program
{
private static void Main(string[] args)
{
IList x = new ArrayList();
for(int i = 0; i < 100000; i++)
{
x.Add(new Person("First #" + i, "Last #" + i));
}
Stopwatch watch1 = new Stopwatch();
watch1.Start();
foreach(Person person in x)
{
Console.Write(person.FirstName);
Console.Write(person.LastName);
}
watch1.Stop();
Stopwatch watch2 = new Stopwatch();
watch2.Start();
IList<Person> persons = ConvertToListOf<Person>(x);
foreach(Person person in persons)
{
Console.Write(person.FirstName);
Console.Write(person.LastName);
}
watch2.Stop();
Console.Clear();
Console.WriteLine("Watch #1: {0}\r\nWatch #2: {1}", watch1.Elapsed, watch2.Elapsed);
Console.Read();
}
public static IList<T> ConvertToListOf<T>(IList iList)
{
IList<T> result = new List<T>();
foreach(T value in iList)
{
result.Add(value);
}
return result;
}
}
public class Person
{
public string FirstName;
public string LastName;
public Person(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
}
}
However it come down to an interesting measurement issue
* Pass through *
Watch #1: 00:00:00.0075761
Watch #2: 00:00:00.0131754
* Pass through & read field *
Watch #1: 00:00:06.2585406 (process direct)
Watch #2: 00:00:06.3542894 (convert first)

Also – you can do the following with Linq
var typedList = list.Cast().ToList();
Patrick Greene
April 16, 2009 at 7:55 pm
There should be a generic type specification on the Cast but brackets were cut out… list.Cast[T]().ToList()
Patrick Greene
April 16, 2009 at 7:56 pm
rodrijp
June 26, 2009 at 3:02 pm