C# 从列表中的所有项目中获取特定属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19962862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:14:37  来源:igfitidea点击:

Get specific property from all items from the list

c#.netlinqlist

提问by inside

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", "Hymanson", 45));
_contactList.Add(new Contact("Hyman", "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.

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

So far I tried:

到目前为止,我尝试过:

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

采纳答案by Mike Perrenoud

You want to use the Selectmethod, not Wherehere:

您想使用该Select方法,而不是Where在这里:

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

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

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

回答by Reda

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