C#将通用列表复制到具有较少列的对象

时间:2018-03-12 02:57:49

标签: c#

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


public class PersonTarget
{
  public string FirstName {get; set;}
}

有没有一种简单的方法可以将Person数据复制到PersonTarget?

我正在使用foreach循环:

        List<Person> people = new List<Person>();
        people.Add(new Person() { FirstName = "John", LastName = "Smith", Email = "test@example.com" });

        List<PersonTarget> peopleCopy = new List<PersonTarget>();

        foreach (var person in people)
        {
            peopleCopy.Add(new PersonTarget() { FirstName = person.FirstName });
        }

1 个答案:

答案 0 :(得分:6)

您可以使用linq:

 peopleCopy = people.Select(p => new PersonTarget() {FirstName = p.FirstName}).ToList();