开发者

How do you create a List<T> from IEnumerable?

开发者 https://www.devze.com 2023-03-30 16:26 出处:网络
I have a DAL method that returns an IEnumerable. I want a list of business objects, List<Person>. H开发者_如何学运维ow do I build the list from the ienumerable return type ? When I inspect the r

I have a DAL method that returns an IEnumerable. I want a list of business objects, List<Person>. H开发者_如何学运维ow do I build the list from the ienumerable return type ? When I inspect the return value in visual studio I see all the properties. i Just need to make the list.

thanks!


If the IEnumerable contains objects of a known type T, you can simply "convert" it to an IEnumerable<T> and then get a list using the ToList extension method:

IEnumerable foo; // obviously this needs to have a "real" value
var list = foo.Cast<T>().ToList();


Just use Enumerable<T>.ToList:

IEnumerable<T> source = // get data from some source;
List<T> list = source.ToList();

Alternatively, there is an overload of List<T> constructor that takes an IEnumerable<T>:

IEnumerable<T> source = // get data from source;
List<T> list = new List<T>(source);

or

List<T> list = new List<T>(// get data from source);


new List<Person>(MyMethod())


You can use the .ToList() when getting the results. Like this:

List<Person> lstPerson = DAL.GetPersonList().ToList();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号