What is the best way to convert a List<T>
to a List<I>
Where type T implements Interface I?
It looks like I can not do an explicit conversion like this:
List<T> myListOfT;
List<I> myListOfI = (List<I>)myListOfT
;
What is the best way to convert a List<T>
to a List<I>
Where type T implements Interface I?
It looks like I can not do an explicit conversion like this:
List<T> myListOfT;
List<I> myListOfI = (List<I>)myListOfT
;
One option is to use Linq IEnumerable<TResult> Cast<TResult>(this IEnumerable source)
. It casts the elements of our first collection to the type you want.
https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.cast?view=netframework-4.7.2
List<I> myListOfI;
List<T> myListOfT = myListOfI.Cast<T>().ToList();