4

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?

Hcabnettek
  • 12,678
  • 38
  • 124
  • 190

3 Answers3

15

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();
vcsjones
  • 138,677
  • 31
  • 291
  • 286
  • 1
    LINQ Cast and ToList *IS* looping and building up a list; it's just hidden. Answer is really there is no way to do this without a loop. – Kevin Brock Jun 02 '12 at 00:19
4

Try this:

enumerable.Cast<IFoo>().ToList();
Dennis
  • 37,026
  • 10
  • 82
  • 150
4

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

bluevector
  • 3,485
  • 1
  • 15
  • 18