c# - 将列表转换为列表<string>

标签 c# linq list

我有以下问题:

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

我有一个包含许多属性的类,我需要将这些类的列表转换为字符串列表,其中字符串表示类中的一个属性。

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.

我需要将其转换为字符串列表的原因是因为我有一个将 List 作为参数的方法,但 SomethingCool 属性包含此列表所需的数据。

注意:我可以在列表上使用 foreach 循环并填充字符串列表,但我正在寻找一种更优雅的方法,也许 LINQ 可以为我做到这一点?

最佳答案

您可以简单地使用Select:

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

Select 所做的是一个投影,它投影每个项目并将它们转换(而不是转换)为另一种形式。

关于c# - 将列表转换为列表<string>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28606585/

相关文章:

c# - 在 C#/WPF 中加速 L-System 渲染器

c# - Microsoft Solver Foundation 位置分散目标

algorithm - 比较 python 中的两个距离列表( float )

python - 如何替换数组中的条目

list - 为什么 Haskell 给出 "ambiguous type variable"错误?

c# - 强制枚举将数字识别为 C# 中的字符串

c# - 如何比较两个有多个点的 "numbers"?

c# - SQL 到 linq 查询

c# - 如何使用 LINQ 对集合进行排序,以便首先出现特定字符串

c# - Linq 查询返回 true 或 false