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

13,944

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();
Share:
13,944
Fiona - myaccessible.website
Author by

Fiona - myaccessible.website

I have a Pluralsight course on web accessibility: Making a Web Form Accessible Web accessibility is more straightforward than you'd think. This course starts with an inaccessible web form and steps through each of the changes necessary to make it accessible, including an introduction to testing with free screen reader software. About Me Director of Software Development at Xibis (web &amp; app development). Blogging about web accessibility at myaccessible.website Please email me at [email protected] or find me on Twitter.

Updated on July 12, 2022

Comments

  • Fiona - myaccessible.website
    Fiona - myaccessible.website almost 2 years

    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.?