23Jul/090
Casting a List of objects
Casting a list of objects is as simple as (using Linq):
List masterList = new List(); var list = masterList.Cast();
If you don't know the type to cast to, it becomes a bit difficult.
MethodInfo m = typeof(System.Linq.Enumerable).GetMethod("Cast").MakeGenericMethod(new Type[] { typeof(Href) });
var result = m.Invoke(typeof(System.Linq.Enumerable), new object[] { masterList });
This works just fine.
However, the result is not a list. This would not be a problem normally. You would just add a .ToList() to the end.
List masterList = new List(); var list = masterList.Cast().ToList();
This does not work the generic way. I thought another Invoke would do the trick. I could not figure out to do that.
Instead I opted for a more simple option. I created a generic method as such:
public void newMethod()
{
var list = masterList .Cast().ToList();
}
To cast a type list you just add the type.
List<object> oList = new List<object>(); List<string> sList = new List<string>(); sList = oList.Cast<string>.ToList();