C#: How to convert a list of objects to a list of a single property of that object?

Viewed 96481

Say I have:

IList<Person> people = new List<Person>();

And the person object has properties like FirstName, LastName, and Gender.

How can I convert this to a list of properties of the Person object. For example, to a list of first names.

IList<string> firstNames = ???
6 Answers
using System.Collections.Generic;
using System.Linq;

IList<Person> people = new List<Person>();
IList<string> firstNames = people.Select(person => person.FirstName).ToList();

This will turn it to a list:

List<string> firstNames = people.Select(person => person.FirstName).ToList();

This will return one (the first one):

var firstname = people.select(e => e.firstname).FirstOrDefault();
Related