[英]C# convert object in a list to another object
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: 当它们在这样的列表中时, PersonORM
使用构造函数将Person
转换为PersonORM
:
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. List<T>
的构造函数不支持它,因此无法使用您所拥有的语法来实现。
If you can use linq (depending on which version of .Net you are targeting), you can do this: 如果可以使用linq(取决于您定位的.Net版本),则可以执行以下操作:
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. 这将使用Select
运算符从原始列表中的每个项目执行转换。
可以使用LINQ完成:
List<PersonORM> peopleOrm = new List<Person>(people.Select(p => new PersonORM(p)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.