2012-03-20 11 views
6

Ho una listaCome posso creare un nuovo elenco dall'elenco esistente?

List<Student> 

class Student{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public string School { get; set; } 
} 

voglio usare questo elenco e creare o compilare i dati in

List<Person> 

class Person{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
} 

Aiutami ..

Thanx

+0

fa classe '' Person' e Student' hanno un qualche tipo di relazione? –

risposta

17

Questo dovrebbe fare il trucco

List<Person> persons = students.Select(student => new Person {FirstName = student.FirstName, LastName = student.LastName}).ToList(); 
+1

+1 linq è il modo per andare qui ... se si evita il fatto che sembra che 'Student' debba ereditare' Person'. – Mizipzor

7

Forse la soluzione più semplice è ereditare lo studente dalla persona (uno studente è una persona).

In questo modo non è necessario copiare/convertire l'elenco.

Il risultato sarebbe qualcosa di simile (fatto senza IDE):

Lista

public class Person{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
} 

class Student : Person{ 
    public string School { get; set; } 
} 

List<Student> ... 

List<Person> ... 
2

Se non v'è alcuna eredità esplicito tra Student e Person puoi utilizzare una proiezione:

List<Student> ls = ...; 

List<Person> lp = 
    ls.Select( 
    student => 
     new Person() 
     { 
      FirstName = student.FirstName, 
      LastName = student.LastName 
     }); 
1

Diciamo che abbiamo

List<Student> k= new List<Student>(); 
//add some students here 
List<Person> p= k.select(s=>new Person() { FirstName = student.FirstName, LastName = student.LastName }); 
1

Mantenere la classe di persona come sta.

class Person { 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
} 

rendere la classe Student derivano da Person e aggiungere la proprietà della scuola.

class Student : Person { 
    public string School { get; set; } 
} 

È ora possibile aggiungere un Student a un elenco di Person s.

var persons = new List<Person>(); 
persons.Add(new Student()); 
1

È possibile compilare i dati in un altro elenco dal seguente modo:

listPerson = (from student in listStudent 
          select new Person 
          { 
           FirstName = student.FirstName, 
           LastName = student.LastName 
          }).ToList<Person>(); 
Problemi correlati