Erik Funkenbusch
Erik Funkenbusch

Reputation: 93424

How to get an array of members of an array

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());
    }
}

Upvotes: 0

Views: 98

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1499860

This one's simple, if I've understood you rightly:

List<Foo> foos = gloop.Foos; // Or wherever you're getting it from
List<Bar> bars = foos.Select(foo => foo.Bar)
                     .ToList();

If you only need an IEnumerable<Bar> you can just use Select without the call to ToList. Of course you don't need the foos local 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 existing List<Foo> or Foo[] (you mention arrays in your subject line).

Upvotes: 2

carlmon
carlmon

Reputation: 406

var bars = gloop.Foos.Select(foo => foo.Bar);

Upvotes: 1

Related Questions