Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert / Cast IEnumerable to IEnumerable<T>

Tags:

c#

linq

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) {} 
like image 668
andleer Avatar asked May 01 '09 18:05

andleer


People also ask

How to cast an IEnumerable to an IEnumerable<T>?

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.

What is cast<TResult> (IEnumerable) in Java?

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.

Is it possible to return an empty list from an IEnumerable?

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 to convert a IEnumerable to list in a createchildcontrols event?

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):


1 Answers

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.

like image 160
Jon Skeet Avatar answered Oct 14 '22 14:10

Jon Skeet