开发者

.Net 4.0 C# - Adding to collections without manual loop

开发者 https://www.devze.com 2023-03-07 22:03 出处:网络
I\'m new to the 4.0 framework (coming from 2.0), and I\'m not entirely sure how to phrase this question so I figured it would be easiest to ask opposed to trying my luck with google.

I'm new to the 4.0 framework (coming from 2.0), and I'm not entirely sure how to phrase this question so I figured it would be easiest to ask opposed to trying my luck with google.

Here's the scenario:

Let开发者_如何学Go's say I have a collection of class "Wheel", and I have a second collection of class "Vehicle", where each vehicle object has a collection of "Wheel". My objective is to add every Vehicle's Wheels to my Wheel collection.

With the extension methods, is there another way to do this:

foreach(Vehicle v in vehicles)
{
   wheels.AddRange(v.Wheels);
}

Or more specifically, in my actual use case there would only be one wheel (I need to add a specific member of each object in a collection to another collection):

foreach(Vehicle v in vehicles)
{
   wheels.Add(v.Wheel);
}

I realize doing the above is pretty simple in itself, but for this project I'd like to use the additions to 3.5/4.0 wherever possible.

Thanks!


A little bit of LINQ will do the trick

wheels.AddRange(vehicles.SelectMany(v => v.Wheels));

Thanks Fourth, I should point out the other case. If there is just one wheel then Select will work:

wheels.AddRange(vehicles.Select(v => v.Wheel));


There is another approach:

vehicles.ForEach(v => { wheels.AddRange(v.Wheels); });

Or in case of one wheel:

vehicles.ForEach(v => { wheels.Add(v.Wheel); });
0

精彩评论

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

关注公众号