【问题标题】:How can I retrieve all property values from a list of common objects?如何从常见对象列表中检索所有属性值?
【发布时间】:2011-01-31 18:14:37
【问题描述】:

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

class Foo{
   public string Bar { get; set; }
   public string Baz { get; set;}
}

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

var list = new List<Foo>();

string[] allBars = list. .... 

怎么回事???

感谢您的帮助。

【问题讨论】:

    标签: c# linq collections extension-methods


    【解决方案1】:

    你可以使用:

    string[] allBars = list.Select(foo => foo.Bar).ToArray();
    

    如果您特别需要将它放在数组中,我只会将其转换为数组。如果您的目标只是输出“Bar”列表,您可以这样做:

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

    【讨论】:

    • 打败我。 Linq 专门设计用于使此类列表转换变得简单而轻松。
    • 感谢您的提示。很好很简单。我将使用它来绑定到 OracleCommand (ODP.NET) 中的数组
    【解决方案2】:
    var query = from foo element in foo_bar_list
                            where foo.Bar == ""
                            select new
                            {
                                class1.Baz
                            };
    

    【讨论】:

      猜你喜欢
      • 2011-10-04
      • 1970-01-01
      • 2017-09-22
      • 2021-07-02
      • 1970-01-01
      • 2013-09-03
      • 2021-08-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多