3

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?


Try this:

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

3 回答 3

13

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();
于 2012-06-01T18:56:30.540 回答
4

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

于 2012-06-01T18:56:15.583 回答
4

尝试这个:

enumerable.Cast<IFoo>().ToList();
于 2012-06-01T18:56:03.940 回答