繁体   English   中英

从一个对象列表复制到具有相同结构的另一个对象

[英]Copy from one list of objects to another with the same structure

如何将所有内容从一个对象列表复制到另一个对象。 这两个对象的结构相同,但名称不同。

这是代码:

 class Program
{
    static void Main(string[] args)
    {
        List<Test> lstTest = new List<Test>();
        List<Test2> lstTest2 = new List<Test2>();

        lstTest.Add(new Test { Name = "j", Score = 2 });
        lstTest.Add(new Test { Name = "p", Score = 3 });

        lstTest2 = lstTest.ConvertAll(x => (Test)x);

    }
}

class Test
{
    private string name;
    private int score;

    public string Name
    {
        get { return name;  }
        set { this.name = value; }
    }

    public int Score
    {
        get { return score; }
        set { this.score = value; }
    }
}

class Test2
{
    private string name;
    private int score;

    public string Name
    {
        get { return name; }
        set { this.name = value; }
    }

    public int Score
    {
        get { return score; }
        set { this.score = value; }
    }
}

我得到的错误是

无法将类型System.Collections.Generic.List<Test>隐式转换为System.Collections.Generic.List<cTest2>

如果您不想使用自动映射器或其他映射工具,则可以使用select和new实例执行以下操作,然后返回一个列表:

lstTest2 = lstTest.Select(e => new Test2()
{
    Score = e.Score,
    Name = e.Name
}).ToList();

对于Automapper,您可以执行以下操作:

var config = new MapperConfiguration(cfg => {

    cfg.CreateMap<Test, Test2>();
});
IMapper iMapper = config.CreateMapper();
lstTest2 = iMapper.Map<List<Test>, List<Test2>>(lstTest);

在配置中,您定义类型转换。 将其从一种映射到另一种类型。

当然,您可以扩展实现以使其通用。

文档参考:

您正在尝试将Test隐式转换为Test2对象。 纠正代码的一种简单方法是构造Test2对象:

lstTest2 = lstTest.ConvertAll(x => new Test2 { Name = x.Name, Score = x.Score });

即使基础结构相同,也无法从TestTest2 如果要显式转换,则必须定义一个转换运算符:

class Test2 {
    // all code of class Test2

    public static explicit operator Test2(Test v)
    {
        return new Test2 { Name = v.Name, Score = v.Score };
    }
}

然后,您可以转换为ConvertAll

lstTest2 = lstTest.ConvertAll(x => (Test2)x);

而不是让两个完全不同的对象使用不同的名称,而是研究如何进行对象继承

class Program
{
    static void Main(string[] args)
    {
        List<TestBase> lstTest = new List<TestBase>();

        lstTest.Add(new Test { Name = "j", Score = 2 });
        lstTest.Add(new Test2 { Name = "p", Score = 3 });
    }
}

class TestBase
{
    private string name;
    private int score;

    public string Name
    {
        get { return name;  }
        set { this.name = value; }
    }

    public int Score
    {
        get { return score; }
        set { this.score = value; }
    }
}

class Test : TestBase { }

class Test2 : TestBase { }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM