Converting a list of one type to a list of another type in C # 3.5

I have an object that has the ID and Name properties.

I have a list of objects, but I want to convert it to a list of strings containing the name of the object. I guess there is some kind of fancy Linq method that will put the name of an object in a list.

List<string> myObjectNames = myObjectList.?
+3
source share
1 answer

If you know that this is specific List<T>and not another type of collection, 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);

, , , LINQ Enumerable<T>.Select Enumerable<T>.ToList:

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

Source: https://habr.com/ru/post/1761294/


All Articles