Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert List Type to IEnumerable Interface Type

Tags:

c#

I have a

List<Person> personlist; 

How can I convert to

IEnumerable<IPerson> iPersonList

Person Implements IPerson interface

like image 843
patrick Avatar asked Feb 25 '13 16:02

patrick


People also ask

Can we convert list to IEnumerable in C#?

We can use the AsEnumerable() function of LINQ to convert a list to an IEnumerable in C#.

How do I cast a list in IEnumerable?

You can use the extension method AsEnumerable in Assembly System. Core and System. Linq namespace : List<Book> list = new List<Book>(); return list.

How to convert IEnumerable List to List in C#?

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();


1 Answers

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>();
like image 171
Rawling Avatar answered Oct 05 '22 01:10

Rawling