[英]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. 我需要将其转换为字符串列表的原因是因为我有一个方法将List作为参数,但SomethingCool属性包含我需要此列表的数据。
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? 注意:我可以在列表中使用foreach循环并填充字符串列表,但我正在寻找更优雅的方法,也许LINQ可以为我做这个吗?
You can simply use Select
: 您只需使用
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. Select
做什么是投影 ,它投影每个项目并将它们转换(不转换)成另一种形式。
Note that you can even: 请注意,您甚至可以:
List<string> theCoolStuff = stuff.ConvertAll(x => x.SomethingCool);
because the List<T>
has a special "conversion" method :-) 因为
List<T>
有一个特殊的“转换”方法:-)
foreach (AwesomeClass member in stuff)
{
theCoolStuff.Add(member. SomethingCool)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.