简体   繁体   English

如何从List的每个元素中提取(在C#中)特定属性,并获取这些属性的新列表?

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

We begin with a List<X> . 我们从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 Zx for every element Z of some List<X> ? X的每个对象都有一个Y类型的属性。你能提出一种优雅的方法来构造一个List,它由一些List<X>每个元素Z的Zx组成吗? I'm sure "manual" iteration over List<X> isn't necessary. 我确信没有必要在List<X> “手动”迭代。 Thanks for any advice. 谢谢你的建议。

If this is List<T> , then: 如果这是List<T> ,那么:

var newList = oldList.ConvertAll(item => item.x);

or with LINQ: 或者使用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: 请注意,在C#2.0中,第一个版本可能需要显式提到的泛型类型:

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. 还有一个静态的Array.ConvertAll ,其行为类似,但对于数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM