Alex Rivera | Logout

Retrieve an array of a property from an array of objects

Asked 2011-07-11T14:34:06.387
11

Assume the following class:

class Person
{
   public string FirstName {get;set;}
   public string LastName {get;set;}
}

Lets say that I have a list or an array of Person object. Is there a way using LINQ to retrieve FirstName property from all the array elements and return an array of string. I have a feeling that I have seen something like that before.

Hope that the question makes sense.

Edit
Report

1 Answer

8

If you have an array, then personally, I'd use:

Person[] people = ...
string[] names = Array.ConvertAll(people, person => person.FirstName);

here; it avoids a few reallocations, and works on more versions of .NET. Likewise:

List<Person> people = ...
List<string> names = people.ConvertAll(person => person.FirstName);

LINQ will work, but isn't actually required here.

answered 2011-07-11T14:38:22.197

Your Answer