-1

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

;

Chad
  • 23,658
  • 51
  • 191
  • 321
  • 2
    All it took to find the duplicate was to google "c# list interface to list class", you should research before posting questions. Also, your question title and body are opposite, which one are you looking for? – Camilo Terevinto Apr 03 '19 at 18:15
  • You changed what you wanted, so I changed the duplicate :) – Camilo Terevinto Apr 03 '19 at 18:19

1 Answers1

1

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();
Justin Lessard
  • 10,804
  • 5
  • 49
  • 61