31

我有联系人列表:

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

    /// <summary>
    /// Constructor
    /// </summary>
    /// <param name="fname">Contact's First Name</param>
    /// <param name="lname">Contact's Last Name</param>
    /// <param name="age">Contact's Age</param>
    public Contact(string fname, string lname, int age)
    {
        _firstName = fname;
        _lastName = lname;
        _age = age;
    }

    /// <summary>
    /// Contact Last Name
    /// </summary>
    public string LastName
    {
        get
        {
            return _lastName;
        }
        set
        {
            _lastName = value;
        }
    }

    /// <summary>
    /// Contact First Name
    /// </summary>
    public string FirstName
    {
        get
        {
           return _firstName;
        }
        set
        {
            _firstName = value;
        }
    }

    /// <summary>
    /// Contact Age
    /// </summary>
    public int Age
    {
        get
        {
            return _age;
        }
        set
        {
            _age = value;
        }
    }
}

在这里我正在创建我的列表:

private List<Contact> _contactList;
_contactList = new List<Contact>();
_contactList.Add(new Contact("John", "Jackson", 45));
_contactList.Add(new Contact("Jack", "Doe", 20));
_contactList.Add(new Contact("Jassy", "Dol", 19));
_contactList.Add(new Contact("Sam", "Josin", 44));

现在我正在尝试使用 LINQ 在单独的列表中获取所有联系人的所有名字。

到目前为止,我尝试过:

    public List<string> FirstNames
    {
        get
        {
           return _contactList.Where(C => C.FirstName.ToList());
        }
    }
4

2 回答 2

54

你想用的Select方法,不在Where这儿:

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

此外,对ToList()唯一的需要是因为property需要它而存在。IEnumerable<string>如果你想摆脱它,你可以返回一个。

于 2013-11-13T19:42:39.360 回答
6
public List<string> FirstNames
{
    get
    {
       return _contactList.Select(C => C.FirstName).ToList();
    }
}
于 2013-11-13T19:43:29.490 回答