Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert List to List<string>

Tags:

c#

list

linq

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?

like image 982
Mike Eason Avatar asked Jun 13 '26 05:06

Mike Eason


2 Answers

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.

like image 88
Selman Genç Avatar answered Jun 14 '26 19:06

Selman Genç


Note that you can even:

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

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

like image 31
xanatos Avatar answered Jun 14 '26 17:06

xanatos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!