在一个列表到另一个对象C#转换对象 [英] C# convert object in a list to another object
本文介绍了在一个列表到另一个对象C#转换对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有可能的对象列表分配给对象的另一个列表中把它作为一个构造函数?
例如:
公共类PersonORM {
公共PersonORM(人p){/ *转换* /}
公众诠释PERSONID {搞定;组; }
/ *这里其它性能* /
}
公共类Person {
公众诠释PERSONID {搞定;组; }
/ *这里其它性能* /
}
如何转换人
到 PersonORM
使用构造时,他们在像这样的列表:
列表<&人GT;人= getPeople();
名单,LT; PersonORM> peopleOrm =新的List<&人GT;(人); //是这样的possoble?
解决方案
这是不可能做到这一点的语法你有作为名单,LT的构造; T>
不支持
如果你可以使用LINQ(视它的.Net你的目标)的版本,你可以这样做:
列表< PersonORM> personOrm = people.Select(p值=>新建PersonORM(P))。了ToList();
这使用的 选择
运营商在原始列表执行从每个项目的转换。
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.
这篇关于在一个列表到另一个对象C#转换对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文