tags:

views:

173

answers:

3

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 = ???
+2  A: 
firstNames = (from p in people select p=>p.firstName).ToList();
Gregoire
Using a query expression in this case is overkill, IMO. Dot notation has less fluff if you've just got one simple operation.
Jon Skeet
True, but the question was "How can this be done" ... not "How can this be done with the least amount of fluff". No disrespect intended, Jon. (Please don't smite me).
Dan Esparza
+15  A: 
List<string> firstNames = people.Select(person => person.FirstName).ToList();

And with sorting

List<string> orderedNames = people.Select(person => person.FirstName).OrderBy(name => name).ToList();
Dario
Thanks. Also, how would I sort that alphabetically by firstname?
User
List<string> firstNames = people.Select(person => person.FirstName).ToList().Sort();This will sort using the default alphabetic sorting of string.
Paul Williams
Sort() doesn't support a fluent interface! Call firstNames.Sort() separately
Dario
My mistake. Dario is right.
Paul Williams
var list = from person in people orderby person.FirstName select person.FirstName;
consultutah
+1  A: 
IList<string> firstNames = (from person in people select person.FirstName).ToList();

Or

IList<string> firstNames = people.Select(person => person.FirstName).ToList();
Jon Sagara