开发者

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:

List<Person> people = getPeople();
List<PersonORM> peopleOrm开发者_C百科 = 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.


It can be done using LINQ:

List<PersonORM> peopleOrm = new List<Person>(people.Select(p => new PersonORM(p)));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜