I'm trying to accomplish the following.
Suppose I have this data model:
public class Article
{
public ICollection<string> Tags { get; set; }
}
These tags are retrieved from a database. My database's API returns them to me as a List<object>
.
Therefore, I need to make a conversion from List<object>
to something that implements ICollection<string>
.
I am aware of the LINQ Cast<T>()
method that cast its elements to the given type and returns the converted IEnumerable<T>
.
However, I cannot use Cast<string>()
because that would always cast my List<object>
to IEnumerable<string>
, not giving any options for models that have ICollection<double>
properties (or any other type).
I can use reflection and get the generic type parameter:
Type genericArg = collectionType.GetGenericArguments().First();
But that would leave me with a runtime Type
, which I cannot use as Cast<genericArg>()
.
How can I cast an IEnumerable<object>
to an IEnumerable
of a dynamic Type
?.
I should note that no complex types are allowed on my model, so anything like:
public ICollection<Tag> Tags { get; set; }
will not happen. I only handle primitive types.