I have a
List<Person> personlist;
How can I convert to
IEnumerable<IPerson> iPersonList
Person Implements IPerson interface
We can use the AsEnumerable() function of LINQ to convert a list to an IEnumerable in C#.
You can use the extension method AsEnumerable in Assembly System. Core and System. Linq namespace : List<Book> list = new List<Book>(); return list.
In C#, an IEnumerable can be converted to a List through the following lines of code: IEnumerable enumerable = Enumerable. Range(1, 300); List asList = enumerable. ToList();
If you're in .NET 4.0 or later, you can just do an implicit cast:
IEnumerable<IPerson> iPersonList = personlist;
//or explicit:
var iPersonList = (IEnumerable<IPerson>)personlist;
This uses generic contravariance in IEnumerable<out T>
- i.e. since you only ever get something out of an IEnumerable
, you can implicitly convert IEnumerable<T>
to IEnumerable<U>
if T : U
. (It also uses that List<T> : IEnumerable<T>
.)
Otherwise, you have to cast each item using LINQ:
var iPersonList = personlist.Cast<IPerson>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With