C# extension method to get list of string from list of customObject
class Pers开发者_C百科on
{
string Name
}
With a List<Person> persons
, what's the extension method to get List<string>
object with each person's Name?
If you really need a List<string>
, then you can use:
persons.Select(p => p.Name).ToList();
But if you only need to enumerate over the values, you can drop the ToList()
:
persons.Select(p => p.Name);
using an extention method:
static class PersonListExtensions
{
public static List<string> ToStringList( this List<Person> persons)
{
return persons.Select(p=>p.Name).ToList();
}
}
精彩评论