开发者

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 ServiceBas开发者_高级运维e 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:

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).


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜