Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

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.?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...