AutoMapper之集合和数组映射

9.集合和数组映射

在项目中,集合和数组使用的很多的,继续下来就讲讲他们的映射,很简单。

/// <summary>
/// 源对象
/// </summary>
public class Source
{
    public int Value { get; set; }
    public string Text { get; set; }
}

/// <summary>
/// 目标对象
/// </summary>
public class Destination
{
    public int Value { get; set; }
    public string Text { get; set; }
}

/// <summary>
/// 集合和数组映射测试类
/// </summary>
[TestClass]
public class ListAndArrayMaping
{
    [TestMethod]
    public void ListMapingTest()
    {
        //初始化映射 和单个对象的映射一样
        Mapper.Initialize(cfg => cfg.CreateMap<Source, Destination>());

        var srcList = new List<Source> {
            new Source { Value = 5,Text="Five" }                
        };

        
	//在这里指定类型参数,拿第一个为例;源类型:List<Source>;目标类型:IEnumerable<Destination>;
	// List映射到IEnumerable;
        IEnumerable<Destination> ienumerableDest1 = Mapper.Map<List<Source>, IEnumerable<Destination>>(srcList);
	// List映射到ICollection;
        ICollection<Destination> icollectionDest1 = Mapper.Map<List<Source>, ICollection<Destination>>(srcList);
        // List映射到IList;
	IList<Destination> ilistDest1 = Mapper.Map<List<Source>, IList<Destination>>(srcList);
	// List映射到List;
        List<Destination> listDest1 = Mapper.Map<List<Source>, List<Destination>>(srcList);
	// List映射到Array;
        Destination[] arrayDest1 = Mapper.Map<List<Source>, Destination[]>(srcList);

        //验证List映射到IEnumerable的结果
        foreach (var m in ienumerableDest1)
        {
            Assert.AreEqual("Five", m.Text);//通过
            Assert.AreEqual(5, m.Value); //通过
        }
        //验证List映射到List结果
        foreach (var m in listDest1)
        {
            Assert.AreEqual("Five", m.Text); //通过
            Assert.AreEqual(5, m.Value); //通过
        }

    }
}

AutoMapper还支持以下集合类型的映射:

  • IEnumerable
  • IEnumerable
  • ICollection
  • ICollection
  • IList
  • IList
  • List
  • Arrays

以后在项目中使用起来就更加方便了!!!

 

出处:https://www.cnblogs.com/wuyunblog/p/6666485.html

=======================================================================================

AutoMapper目录

 

出处:https://www.cnblogs.com/wuyunblog/tag/AutoMapper/

posted on   jack_Meng  阅读(849)  评论(0编辑  收藏  举报

编辑推荐:
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· DeepSeek “源神”启动!「GitHub 热点速览」
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器
历史上的今天:
2015-09-08 正十二面体的走访
2015-09-08 计算等差数列之和
2014-09-08 用ICSharpCode.SharpZipLib进行压缩
2014-09-08 System.Data.SQLite数据库简介

导航

< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8
点击右上角即可分享
微信分享提示

喜欢请打赏

扫描二维码打赏

支付宝打赏

主题色彩