Convert list of one type to list of another type in C# 3.5

感情迁移 提交于 2020-01-24 10:14:05

问题


I have an object, with ID and Name properties.

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.

List<string> myObjectNames = myObjectList.?

回答1:


If you know it is specifically a List<T> and not another collection type then you can use List<T>.ConvertAll:

Converts the elements in the current List<T> to another type, and returns a list containing the converted elements.

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:

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


来源:https://stackoverflow.com/questions/3555661/convert-list-of-one-type-to-list-of-another-type-in-c-sharp-3-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!