We begin with a List<X>
. Every object of X has an attribute x of type Y. Could you propose an elegant way to construct a List which is composed of the Z.x
for every element Z of some List<X>
?
I'm sure "manual" iteration over List<X>
isn't necessary. Thanks for any advice.
If this is List<T>
, then:
var newList = oldList.ConvertAll(item => item.x);
or with LINQ:
var newList = oldList.Select(item => item.x).ToList();
Note that in C# 2.0 the first version might need the generic type mentioned explicitly:
List<Y> newList = oldList.ConvertAll<Y>(delegate (X item) { return item.x; });
(but that is actually 100% identical to the first line)
There is also a static Array.ConvertAll
which behaves similarly, but for arrays.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With