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.
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 });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With