简体   繁体   English

将一种类型的列表转换为C#3.5中另一种类型的列表

[英]Convert list of one type to list of another type in C# 3.5

I have an object, with ID and Name properties. 我有一个具有ID和Name属性的对象。

I have a list of the objects, but I want to convert it to a list of strings containing the name of the object. 我有一个对象列表,但我想将其转换为包含对象名称的字符串列表。 I'm guessing there's some fancy Linq method that will put the name of the object into the list. 我猜测有一些花哨的Linq方法会将对象的名称放入列表中。

List<string> myObjectNames = myObjectList.?

If you know it is specifically a List<T> and not another collection type then you can use List<T>.ConvertAll : 如果你知道它是一个List<T>而不是另一个集合类型,那么你可以使用List<T>.ConvertAll

Converts the elements in the current List<T> to another type, and returns a list containing the converted elements. 将当前List<T>的元素转换为另一种类型,并返回包含已转换元素的列表。

Example: 例:

List<string> myObjectNames = myObjectList.ConvertAll(x => x.Name);

If you just know that it is an enumerable type but not necessarily a list then you can use the LINQ extension methods Enumerable<T>.Select and Enumerable<T>.ToList : 如果您只知道它是一个可枚举类型但不一定是列表,那么您可以使用LINQ扩展方法Enumerable<T>.Select and Enumerable<T>.ToList

List<string> myObjectNames = myObjects.Select(x => x.Name).ToList();

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

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