如何从常用对象列表中检索所有属性值?

Mac*_*acX 1 c# linq collections extension-methods

我想从集合中检索所有单个属性作为数组:

class Foo{
   public string Bar { get; set; }
   public string Baz { get; set;}
}
Run Code Online (Sandbox Code Playgroud)

我想从集合中获取所有Bar属性

var list = new List<Foo>();

string[] allBars = list. .... 
Run Code Online (Sandbox Code Playgroud)

它是怎么回事?

谢谢你的帮助.

Ree*_*sey 11

您可以使用:

string[] allBars = list.Select(foo => foo.Bar).ToArray();
Run Code Online (Sandbox Code Playgroud)

如果您特别需要将它转换为数组,我只会将其转换为数组.如果您的目标只是输出"条形码"列表,您可以这样做:

var allBars = list.Select(foo => foo.Bar); // Will produce IEnumerable<string>
foreach(var bar in allBars)
{
    // Do something with bar
}
Run Code Online (Sandbox Code Playgroud)