Search code examples
c#arrayssub-array

get property of array as new array c#


Suppose I have a class like the following:

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

And somewhere later I have an array Book[] books and now want an array of the titles string[] titles = {books[0].title, books[1].title, ..., books[n].title}. Is there an easier way than looping over the books array? Something like

string[] titles = books.getProperty(title)

Thanks in advance


Solution

  • Generally, you would use Linq methods to manipulate collections, for example (Select & ToArray):

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

    However, since this is an array and you an array as a result, you can also use some static methods on the Array type (ConvertAll):

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