How to create a new list from an existing list?

I have a list

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

I want to use the above list and create or populate this data in

 List<Person> class Person{ public string FirstName { get; set; } public string LastName { get; set; } } 

Help me..

Thanx

+6
source share
6 answers

That should do the trick

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

Perhaps the simplest solution is to inherit the Student from the Person (the student is a person).

This way you do not need to completely copy / convert the list.

The result will be something like (done without an IDE):

List

 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> ... 
+7
source

If there is no explicit inheritance between Student and Person , you can use projection:

 List<Student> ls = ...; List<Person> lp = ls.Select( student => new Person() { FirstName = student.FirstName, LastName = student.LastName } ); 
+2
source

Let's say that

 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
source

Keep the person class as is.

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

Create a Student class from Person and add the School property.

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

Now you can add Student to the Person s list.

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

You can fill in the data in another list as follows:

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

Source: https://habr.com/ru/post/911185/


All Articles