16

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 above list and create or fill that data into

List<Person>

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

Help me..

Thanx

1
  • does class Person and Student have some kind of relation? Commented Mar 20, 2012 at 11:00

6 Answers 6

34

That should do the trick

List<Person> persons = students.Select(student => new Person {FirstName = student.FirstName, LastName = student.LastName}).ToList();
Sign up to request clarification or add additional context in comments.

1 Comment

+1 linq is the way to go here... if you avoid the fact that it looks like Student should inherit Person.
7

Maybe the easiest solution is to inherit Student from Person (a student IS a person).

This way you don't have to copy/convert the list at all.

The result would be something like (done without 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> ...

Comments

4

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

List<Student> ls = ...;

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

Comments

1

Let's say we have

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

Comments

1

Keep the person class as is.

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

Make the Student class derive from Person and add the School property.

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

You can now add a Student to a List of Persons.

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

Comments

1

You can fill data into another list by following way:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.