Get specific property from all items from the list

前端 未结 2 352
春和景丽
春和景丽 2020-12-15 04:27

I have list of Contacts:

public class Contact
{
    private string _firstName;
    private string _lastName;
    private int _age;

    /// 
         


        
相关标签:
2条回答
  • 2020-12-15 04:52
    public List<string> FirstNames
    {
        get
        {
           return _contactList.Select(C => C.FirstName).ToList();
        }
    }
    
    0 讨论(0)
  • 2020-12-15 05:00

    You want to use the Select method, not Where here:

    _contactList.Select(C => C.FirstName).ToList();
    

    Further, the need for the ToList() only exists because the property demands it. You could return an IEnumerable<string> instead if you wanted to get rid of that.

    0 讨论(0)
提交回复
热议问题