Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need a Linq IEnumerable<>.Cast(typeof(T))

I'm querying a data structure and the result type is IEnumerable<IEntry> (IEntry being a framework interface), each entry has a Data property (of type object) which is interseting for me.

My code looks like this:

var resultList = framework.QueryAllOfType(queryClause.Type)
                          .Select(e => e.Data)
                          .ToList();
deleagte.DynamicInvoke(new[]{resultList});

The method behind the delegate looks something like this:

void Foo (IEnumerable<SomeType> bar); // if queryClause.Type == typeof(SomeType)
void Foo (IEnumerable<OtherType> bar); // if queryClause.Type == typeof(OtherType)

I'm absolutely positive that queryClause.Type matches SomeType, of course however, the .NET framework is not ;-)

Unfortunately this means that the resultList is of type IEnumerable<object> although all the objects within are of the correct type, I'm not able to call the delegate (exception: IEnumerable<object> cannot be converted into IEnumerable<SomeType>).

I know why this is the case, but what's the solution? I would need something along the lines of:

.Select(e => e.Data).Cast(queryClause.Type).ToList() which should return an IEnumerable<queryClause.Type>. Is there such a thing already somewhere in the .NET framework? Is there a better solution?

Important: As two answers already misunderstood my intensions, I cannot use the type as a generic parameter as it is known at runtime only. Therefore all Cast<...>(), Select(e =e as ...), etc. do not work.

like image 657
D.R. Avatar asked Sep 02 '25 03:09

D.R.


1 Answers

You can invoke Cast using reflection:

var method = typeof(Enumerable).GetMethod("Cast").MakeGenericMethod(queryClause.Type);
IEnumerable<object> cSeq = (IEnumerable<object>)method.Invoke(null, new object[] { resultList });

deleagte.DynamicInvoke(new[]{ cSeq });
like image 161
Lee Avatar answered Sep 05 '25 01:09

Lee