Mike Eason
Mike Eason

Reputation: 9723

Convert List to List<string>

I have the following problem:

public class AwesomeClass
{
    public string SomethingCool { get; set; }
    public string SomethingUseless { get; set; }
}

I have a class which contains a number of properties, and I need to convert a list of these classes into a list of strings, where the string represents a property in the class.

List<AwesomeClass> stuff = new List<AwesomeClass>();

//Fill the stuff list with some tings.

List<string> theCoolStuff = //Get only the SomethingCool property in the AwesomeClass list.

The reason why I need to convert this to a list of strings is because I have a method which takes a List as a parameter, but the SomethingCool property contains the data that I need for this list.

Note: I could use a foreach loop on the list and populate the List of strings but I'm looking for a more elegant method, perhaps LINQ can do this for me?

Upvotes: 2

Views: 132

Answers (3)

xanatos
xanatos

Reputation: 111940

Note that you can even:

List<string> theCoolStuff = stuff.ConvertAll(x => x.SomethingCool);

because the List<T> has a special "conversion" method :-)

Upvotes: 3

apomene
apomene

Reputation: 14389

foreach (AwesomeClass member in stuff)
{
   theCoolStuff.Add(member. SomethingCool)
}

Upvotes: 0

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101721

You can simply use Select:

var theCoolStuff = stuff.Select(x => x.SomethingCool).ToList();

What Select does is a projection, it projects each item and transforms (not convert) them into another form.

Upvotes: 13

Related Questions