从对象列表生成字符串列表

NoB*_*Man 3 .net c# linq

我有一个对象列表。我对将每个对象的一个​​属性(一个字符串值)隔离到字符串列表中很感兴趣。如何仅使用此字段(最好使用Linq而不手动循环)创建字符串列表?

class MyObj
{
  int ID {get;set;}
  int AnotherID (get;set;}
  string IneedThis {get;set;}
}

List<MyObj> sampleList = somehow_this_is_populated();
List<string> ls = how do I get this list with values equal to "sampleList.IneedThis"
Run Code Online (Sandbox Code Playgroud)

Hab*_*bib 5

您可以Select在您的媒体资源中创建一个类似于以下内容的列表:

List<string> ls = sampleList.Select(item => item.IneedThis).ToList();
Run Code Online (Sandbox Code Playgroud)

确保包含 using System.Linq;

您还可以使用foreach类似的循环来实现相同目的:

List<string> ls = new List<string>();
foreach (MyObj myObj in sampleList)
{
    ls.Add(myObj.IneedThis);
}
Run Code Online (Sandbox Code Playgroud)

确保您在类中的属性为public。然后,在您当前的课程中,没有访问修饰符,系统将予以考虑private。像这样定义它们:

public string IneedThis { get; set; }
Run Code Online (Sandbox Code Playgroud)