复制列表<a> to List<b> when both types share some or all properties

时间:2017-11-29 15:31:22

标签: c# linq

I have two similar classes in two different namespaces:

public class A
{
    public string Id { get; set; }
    public string Description { get; set; }
}

public class B
{
    public string Id { get; set; }
    public string Description { get; set; }
}

I want to create List<B> based on values in a List<A>.

I am doing it the old-fashioned way:

List<A> listA = new List<A>();
// load some values in listA.

List<B> listB = new List<B>();

foreach (var item in listA)
{
    B b = new B()
    {
        Id = item.Id,
        Description = item.Description
    };
    listB.Add(b);
}

This is fine as long as there is a small number of properties in both classes, however, there are more than 15 properties in some classes.

Is there a better/efficient way to copy lists to avoid writing lengthy code?

0 个答案:

没有答案