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

时间:2009-09-22 16:14:44

标签: c# linq list

说我有:

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

person对象具有FirstName,LastName和Gender等属性。

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

IList<string> firstNames = ???

6 个答案:

答案 0 :(得分:138)

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

并进行排序

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

答案 1 :(得分:4)

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

或者

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

答案 2 :(得分:3)

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

答案 3 :(得分: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; }
    }
}

答案 4 :(得分:0)

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

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

答案 5 :(得分:-2)

这会将它变成一个列表:

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

这将返回一个(第一个):

var firstname = people.select(e => e.firstname).FirstOrDefault();