Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

c# - Get specific property from all items from the list

I have list of Contacts:

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;
        }
    }
}

and here I am creating my list:

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));

Right now I am trying to get all the first names of all the contacts in separate list using LINQ.

So far I tried:

    public List<string> FirstNames
    {
        get
        {
           return _contactList.Where(C => C.FirstName.ToList());
        }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...