Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IEnumerable<T> to List<T>

Tags:

c#

c#-4.0

Ok I have looked all around and can't find an answer. I have a method that returns an

IEnumerable<ICar> 

and the calling method is storing the results of the method in

List<ICar> 

but I get the following error.

System.Collections.Generic.IEnumerable<Test.Interfaces.ICar> to 
System.Collections.Generic.List<Test.Interfaces.ICar>. An explicit conversion exists   
(are you missing a cast?)   

I looked on msdn at

IEnumerable<T> interface and List<T> class. 

The following line is from msdn.

public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection,   
IEnumerable

I just don't understand why I can't assign

IEnumerable<ICar> to List<ICar>. 

Can someone please explain this to me. What am I missing.

like image 230
Cam Avatar asked Dec 09 '22 00:12

Cam


2 Answers

Not all IEnumerable<T> are List<T>. The reverse is true.

You can either try to cast to List<T> which is bad practice and could fail if it really is not a list or you can create a new list from the enumeration

new List<T>(yourEnumerable);

or using Linq

yourEnumerable.ToList();
like image 113
aqwert Avatar answered Dec 28 '22 01:12

aqwert


List<ICar> implements IEnumerable<ICar> - you're correct. But that means that you can implicitly convert a List<ICar> to an IEnumerable<ICar> - not the other way around. To get around your problem, just call ToList() on the IEnumerable to convert it to a List.

like image 42
Ry- Avatar answered Dec 28 '22 02:12

Ry-