wake-up-neo.com

C #: Wie konvertiert man eine Liste von Objekten in eine Liste einer einzigen Eigenschaft dieses Objekts?

Sag ich habe:

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

Das Personenobjekt verfügt über Eigenschaften wie Vorname, Nachname und Geschlecht.

Wie kann ich dies in eine Liste von Eigenschaften des Personenobjekts konvertieren? Zum Beispiel zu einer Liste von Vornamen.

IList<string> firstNames = ???
76
User
List<string> firstNames = people.Select(person => person.FirstName).ToList();

Und mit dem Sortieren

List<string> orderedNames = people.Select(person => person.FirstName).OrderBy(name => name).ToList();
131
Dario
IList<string> firstNames = (from person in people select person.FirstName).ToList();

Oder

IList<string> firstNames = people.Select(person => person.FirstName).ToList();
4
Jon Sagara
firstNames = (from p in people select p=>p.firstName).ToList();
3
Gregoire
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; }
    }
}
1
Mohd Shahnawaz
using System.Collections.Generic;
using System.Linq;

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