Base on your feedback and using the other answers I've created a ToListOfType()
extension method that should do what you need.
public static class EnumerableExtensions
{
private static readonly Type _enumerableType = typeof(Enumerable);
public static IEnumerable CastAsType(this IEnumerable source, Type targetType)
{
var castMethod = _enumerableType.GetMethod("Cast").MakeGenericMethod(targetType);
return (IEnumerable)castMethod.Invoke(null, new object[] { source });
}
public static IList ToListOfType(this IEnumerable source, Type targetType)
{
var enumerable = CastAsType(source, targetType);
var listMethod = _enumerableType.GetMethod("ToList").MakeGenericMethod(targetType);
return (IList)listMethod.Invoke(null, new object[] { enumerable });
}
}
This should work with your delegate if you simply replace your ToList()
call with ToListOfType(queryClause.Type)
. I implemented both the CastAsType
and ToListOfType
methods so that you can leave the collection un-iterated if you so choose. I'll note for future readers that these are only useful in a situation like yours where you're passing the result off to a delegate dynamically - the Cast<T>
operation would be preferred in all other cases.