How can I convert IEnumerable<object> to List<IFoo> where each object is an IFoo?

亡梦爱人 提交于 2019-12-23 19:51:56

问题


How can I convert IEnumerable<object> to List<IFoo> where each object is an IFoo?

I have an IEnumerable<object>, someCollection, and each item in someCollection is an IFoo instance. How can I convert someCollection into a List<IFoo>? Can I use convert or cast or something instead of looping through and building up a list?


回答1:


Using LINQ, you can use Cast to cast the items, and use ToList to get a list.

Try:

 IEnumerable<object> someCollection; //Some enumerable of object.
 var list = someCollection.Cast<IFoo>().ToList();



回答2:


someCollection.Cast<IFoo>().ToList()




回答3:


Try this:

enumerable.Cast<IFoo>().ToList();


来源:https://stackoverflow.com/questions/10855836/how-can-i-convert-ienumerableobject-to-listifoo-where-each-object-is-an-ifoo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!