Suppose I have a class
public class Foo
{
public Bar Bar { get; set; }
}
Then I have another class
public class Gloop
{
public List<Foo> Foos { get; set; }
}
What’s the easiest way to get a List<Bar> of Foo.Bars?
I’m using C# 4.0 and can use Linq if that is the best choice.
UPDATE:
Just for a little dose of reality, the reason for this is that I have a Windows Service class that contains an inner ServiceBase derived class as a property. So I end up with code like this:
public class Service
{
public ServiceBase InnerService { get; set; }
}
public class ServiceHost
{
private List<Service> services = new List<Service>();
static void Main()
{
// code to add services to the list
ServiceBase.Run(services.Select(service => service.InnerService).ToArray());
}
}
This one’s simple, if I’ve understood you rightly:
If you only need an
IEnumerable<Bar>you can just useSelectwithout the call toToList. Of course you don’t need thefooslocal variable if you don’t want it – you can just have a single statement. I’ve only separated them out in case you’ve got an existingList<Foo>orFoo[](you mention arrays in your subject line).