I have a class (A web control) that has a property of type IEnumerable and would like to work with the parameter using LINQ.
Is there any way to cast / convert / invoke via reflection to IEnumerable<T> not knowing the type at compile time?
Method void (IEnumerable source) { var enumerator = source.GetEnumerator(); if (enumerator.MoveNext()) { var type = enumerator.Current.GetType(); Method2<type>(source); // this doesn't work! I know! } } void Method2<T>(IEnumerable<T> source) {}
To cast an IEnumerable to an IEnumerable<T>, you can use this code: C#. Copy Code. IEnumerable ienumerable = new int [] { 1, 5, 6, 7, 8, 11, 10, 134, 90 }; IEnumerable casted = ienumerable.Cast<int> (); // change 'int' into the //type of the elements in your IEnumerable. Now, you can use a LINQ query for casted.
An IEnumerable<T> that contains each element of the source sequence cast to the specified type. source is null. An element in the sequence cannot be cast to type TResult. The following code example demonstrates how to use Cast<TResult> (IEnumerable) to enable the use of the standard query operators on an ArrayList.
You can call .AsQueryable () on an IEnumerable<T> sequence and it will return IQueryable<T>. But I would seriously question why you'd want to do this. Returning an empty list in case of an exception is almost always a bad pattern - if an unknown exception is thrown, you really want to let that exception bubble up.
How i convert a IEnumerable to List in a CreateChildControls event? Usually one would use the IEnumerable<T>.ToList () extensionmethod from Linq but in your case you can not use it (right away) because you have the non-generic IEnumerable interface. Sou you will have to cast it first (also using Linq):
Does your Method2
really care what type it gets? If not, you could just call Cast<object>()
:
void Method (IEnumerable source) { Method2(source.Cast<object>()); }
If you definitely need to get the right type, you'll need to use reflection.
Something like:
MethodInfo method = typeof(MyType).GetMethod("Method2"); MethodInfo generic = method.MakeGenericMethod(type); generic.Invoke(this, new object[] {source});
It's not ideal though... in particular, if source isn't exactly an IEnumerable<type>
then the invocation will fail. For instance, if the first element happens to be a string, but source is a List<object>
, you'll have problems.
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