C#:如何将对象列表转换为该对象的单个属性的列表?


104

说我有:

IList<Person> people = new List<Person>();

并且person对象具有FirstName,LastName和Gender之类的属性。

如何将其转换为Person对象的属性列表。例如,以名字列表。

IList<string> firstNames = ???

Answers:


179
List<string> firstNames = people.Select(person => person.FirstName).ToList();

并进行排序

List<string> orderedNames = people.Select(person => person.FirstName).OrderBy(name => name).ToList();

谢谢。另外,我该如何按名字的字母顺序进行排序?
用户

List <string> firstNames = people.Select(person => person.FirstName).ToList()。Sort(); 这将使用默认的字符串字母排序进行排序。
Paul Williams

Sort()不支持流畅的界面!分别调用firstNames.Sort()
Dario

var list =从人员中按人员排序的人员。按person.FirstName选择person.FirstName;
ConsultUtah

最好的答案之一!(可能是我的无知):)
nawfal 2012年

5
IList<string> firstNames = (from person in people select person.FirstName).ToList();

要么

IList<string> firstNames = people.Select(person => person.FirstName).ToList();

3
firstNames = (from p in people select p=>p.firstName).ToList();

7
在这种情况下,使用查询表达式是过大的,IMO。如果您只有一个简单的操作,则点符号的起毛更少。
乔恩·斯基特

1
是的,但问题是“如何做到这一点”……而不是“如何用最少的绒毛做到这一点”。乔恩,不要无礼。(请不要打我)。
Dan Esparza

1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace TestProject
{
    public partial class WebForm3 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            SampleDataContext context = new SampleDataContext();
            List<Employee> l = new List<Employee>();
            var qry = from a in context.tbl_employees where a.Gender=="Female"  
                orderby  a.Salary ascending
            select new Employee() {
                           ID=a.Id,
                           Fname=a.FName,
                           Lname=a.Lname,
                           Gender=a.Gender,
                           Salary=a.Salary,
                           DepartmentId=a.DeparmentId
            };
            l= qry.ToList();
            var e1 =  from  emp in context.tbl_employees
                where emp.Gender == "Male"
                orderby emp.Salary descending
                select  emp;
            GridView1.DataSource = l;
            GridView1.DataBind();
        }
    }
    public class Employee
    {
        public Int64 ID { get; set; }
        public String Fname { get; set; }
        public String Lname { get; set; }
        public String Gender { get; set; }
        public decimal? Salary { get; set; }
        public int? DepartmentId { get; set; }
    }
}

0
using System.Collections.Generic;
using System.Linq;

IList<Person> people = new List<Person>();
IList<string> firstNames = people.Select(person => person.FirstName).ToList();

感谢您提供此代码段,它可能会提供一些有限的短期帮助。通过说明为什么这是一个很好的解决方案,正确的解释将大大提高其长期价值,对于其他有类似问题的读者来说,这将是更加有用的。请编辑您的答案以添加一些解释,包括您所做的假设
Shawn
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.