【问题标题】:Get specific property from all items from the list从列表中的所有项目中获取特定属性
【发布时间】:2013-11-26 14:10:04
【问题描述】:

我有联系人列表:

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

【问题讨论】:

  • 只是给你班级中的访问者的一个注释,你可以简单地在一行上输入public int Age {get; set; } all 而不是你所拥有的,因为你没有在访问者中执行任何其他操作。显然,它更短且更易于阅读。
  • Where 用于评估 Select 条件,例如:foreach contact where (firstname begin with "J") select (contact)

标签: c# .net linq list


【解决方案1】:
public List<string> FirstNames
{
    get
    {
       return _contactList.Select(C => C.FirstName).ToList();
    }
}

【讨论】:

    【解决方案2】:

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

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

    此外,对ToList() 的需求只是因为property 需要它而存在。如果您想摆脱它,可以返回 IEnumerable&lt;string&gt;

    【讨论】:

    • @Stanislav,很高兴能为您提供帮助!
    • 如果 FirstName 是动态的,可能来自字符串形式的参数怎么办?
    • @ibubi 如果FirstName 是动态的,那么您需要将其转换为Select 表达式。
    猜你喜欢
    • 2019-12-18
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 2011-11-22
    • 1970-01-01
    • 1970-01-01
    • 2019-05-29
    相关资源
    最近更新 更多