How to extract (in C #) a specific attribute from each element of the list and get a new list of these attributes?

Let's start with a List<X>. Each object X has an attribute x of type Y. Could you suggest an elegant way to build a list consisting of Z.xfor each element Z some List<X>? I am sure that β€œmanual” iteration is List<X>not needed. Thanks for any advice.

+5
source share
1 answer

If it 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 of the first version, you may need an explicitly specified generic type:

List<Y> newList = oldList.ConvertAll<Y>(delegate (X item) { return item.x; });

(but this is actually 100% identical to the first line)

Array.ConvertAll, , .

+10

All Articles