【问题标题】:get property of array as new array c#将数组的属性作为新数组c#
【发布时间】:2019-10-26 02:39:51
【问题描述】:

假设我有一个像下面这样的类:

class Book
{
    public int id;
    public string title;
}

稍后我有一个数组Book[] books,现在想要一个标题数组string[] titles = {books[0].title, books[1].title, ..., books[n].title}。有没有比循环books 数组更简单的方法?类似的东西

string[] titles = books.getProperty(title)

提前致谢

【问题讨论】:

    标签: c# arrays sub-array


    【解决方案1】:

    通常,您会使用Linq 方法来操作集合,例如(Select & ToArray):

    var titles = books.Select(x => x.title).ToArray();
    

    但是,由于这是一个数组,因此您是一个数组,您还可以在 Array 类型 (ConvertAll) 上使用一些静态方法:

    var titles = Array.ConvertAll(books, x => x.title);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-02
      • 2011-04-25
      • 2022-01-08
      • 1970-01-01
      • 2015-11-12
      • 2016-11-13
      相关资源
      最近更新 更多