Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract (in C#) a specific attribute from every element of a List, and get a new List of these attributes?

Tags:

c#

list

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.

like image 747
user1046221 Avatar asked Nov 18 '11 11:11

user1046221


1 Answers

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.

like image 191
Marc Gravell Avatar answered Nov 14 '22 22:11

Marc Gravell