Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to get a List of a property of T from a List<T>

Tags:

c#

I've got a List<Users> - Users have a Username property.

What I want to know is - is there an better way to get a List<string> of all the Usernames than to simply loop through and build up my new list?

like image 393
Andy Avatar asked Sep 07 '10 14:09

Andy


2 Answers

Use LINQ:

List<string> usernames = users.Select(u => u.UserName).ToList();
like image 70
Arcturus Avatar answered Sep 17 '22 13:09

Arcturus


Like this:

List<string> userNames = users.ConvertAll(u => u.UserName);

Note that the userNames list will not reflect subsequent changes to the users or their UserNames.

like image 35
SLaks Avatar answered Sep 21 '22 13:09

SLaks