Get an array of properties from an array of objects

Assume the following class:

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

Suppose I have a list or array of a Person object. Is there a way to use LINQ to retrieve the FirstName property from all elements of an array and return a string array. I feel like I’ve seen something like this before.

Hope the question makes sense.

+4
source share
3 answers

Of course, very easy:

 Person[] people = ...; string[] names = people.Select(x => x.FirstName).ToArray(); 

If you really need the result to be an array, I would consider using ToList() instead of ToArray() and potentially just leaving it as a lazily evaluated IEnumerable<string> (i.e. just calling Select ), It depends on what you are going to do with the results.

+10
source

If you have an array, then personally I would use:

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

here; it avoids multiple redistributions and works with other versions of .NET. Similar:

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

LINQ will work, but not really required here.

+3
source

Try the following:

 List<Person> people = new List<Person>(); people.Add(new Person() { FirstName = "Brandon", LastName = "Zeider" }); people.Add(new Person() { FirstName = "John", LastName = "Doe" }); var firstNameArray = people.Select(p => p.FirstName).ToArray(); 
+1
source

All Articles