Is it possible to assign list of objects to another list of objects that takes it as a constructor?
Eg.
public class PersonORM{
public PersonORM(Person p){ /* convert */ }
public int PersonId { get; set; }
/* Other properties here */
}
public class Person{
public int PersonId { get; set; }
/* Other properties here */
}
How do I convert Person
to PersonORM
using the constructor when they are in a list like this:
List<Person> people = getPeople();
List<PersonORM> peopleOrm = new List<Person>(people); // Is something like this possoble?
It is not possible to do that with the syntax you have as the constructor of List<T>
does not support it.
If you can use linq (depending on which version of .Net you are targeting), you can do this:
List<PersonORM> personOrm = people.Select(p => new PersonORM(p)).ToList();
This uses the Select
operator to perform the conversion from each item in the original list.
可以使用LINQ完成:
List<PersonORM> peopleOrm = new List<Person>(people.Select(p => new PersonORM(p)));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.