zoukankan      html  css  js  c++  java
  • 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

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

  • 相关阅读:
    POJ 3831 &amp; HDU 3264 Open-air shopping malls(几何)
    LeetCode Maximum Depth of Binary Tree
    解决下载Android Build-tools 19.1.0失败
    cocos2d-x3.6 连连看随机地图实现
    Swift初体验(三)
    Delphi XE7中新并行库
    mysql 权限控制具体解释
    C实例--推断一个字符串是否是回文数
    阿里 2014校招机试题 求存放整数的二叉树相差最大的两节点之差绝对值
    Choosing Between ElasticSearch, MongoDB &amp; Hadoop
  • 原文地址:https://www.cnblogs.com/wuyunblog/p/6666485.html
Copyright © 2011-2022 走看看