Convert IEnumerable to IEnumerable <T> when T is unknown before execution
How to convert IEnumerable to IEnumerable<T> when T is unknown before execution?
I have a method that IEnumerable<T> absolutely needs, where T is unknown until the execution time and T should not be the actual type, and not an object of the ancestor type, strong>.
I am sure that the reflection API allows something like this, but I donβt know exactly how to do this.
Update
I can get an object of type like this:
var first = results.Cast<object>().FirstOrDefault(); if (first != null) { var type = first.GetType(); } Update2
The "method" I was referring to was actually the Setter property of the ItemGource DataGrid WPF. The problem I am facing is that if I do not pass it an IEnumerable<T> , the rows generated in the Datagrid are empty, as if the T property reflection method does not work, and it cannot generate columns.
Even when using this code, this unwanted effect:
public CollectionResultWindow(IEnumerable results) { Contract.Requires(results != null, "results is null."); InitializeComponent(); DataContext = this; var first = results.Cast<object>().FirstOrDefault(); if (first != null) { Type type = first.GetType(); var castMethod = typeof(Enumerable).GetMethod("Cast").MakeGenericMethod(type); dynamic genericResults = castMethod.Invoke(null, new[] { results }); Results = genericResults; // Results is a dependency property that DataGrid.ItemSource is bound to. } } var elementType = ... var results = ... var castMethod = typeof(Enumerable).GetMethod("Cast").MakeGenericMethod(elementType); var genericResults = castMethod.Invoke(null, new[] { results }); The genericResults variable refers to an object of type IEnumerable<T> (where T is the type represented by the variable elementType ). But keep in mind that statically genericResults is still of type object ; There is no way to tell the compiler that this is IEnumerable<T> , since T not known statically.
Here is the code that worked for me:
public CollectionResultWindow(IEnumerable results) { Contract.Requires(results != null, "results is null."); InitializeComponent(); DataContext = this; var first = results.Cast<object>().FirstOrDefault(); if (first != null) { Type type = first.GetType(); var castMethod = typeof(Enumerable).GetMethod("ToList").MakeGenericMethod(type); dynamic genericResults = castMethod.Invoke(null, new[] { results }); Results = genericResults; // Results is a dependency property that DataGrid.ItemSource is bound to. } }