zoukankan      html  css  js  c++  java
  • 两个泛型实例之间的属性变化

    两个泛型实例之间的属性变化,需要借助Linq(select)以及一个新的方法,该方法接受的参数应为属性较全的泛型实例中的元素。

     一、类定义

    public class Person
    {
        public Person(string name, int age, List<string> hobbies)
        {
            Name = name;
            Age = age;
            Hobbies = hobbies;
        }
        public string Name { get; set; }
        public int Age { get; set; }
        public List<string> Hobbies { get; set; }
    }
    
    public class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public List<string> Hobbies { get; set; }
        public List<string> Teachers { get; set; }
    }
    
    public class StudentAndTeacherRelationship
    {
        public StudentAndTeacherRelationship(string studentName, List<string> teachers)
        {
            StudentName = studentName;
            Teachers = teachers;
        }
        public string StudentName { get; set; }
        public List<string> Teachers { get; set; }
    }

    二.具体代码

    static void Main(string[] args)
    {
        var ThreePerson = new List<Person>()
        {
            new Person("frankie", 22, new List<string>() {"Play basketball", "running"}),
            new Person("asan", 23, new List<string>() {"reading", "play games"}),
            new Person("Qin", 24, new List<string>() {"running", "coding"})
        };
        // 不同类型对象之间的属性映射
        Mapper.Initialize(_ => _.CreateMap<Person, Student>());
        var ThreeStudent = Mapper.Map<List<Student>>(ThreePerson);
    
        // 通过Linq语句和一个方法,进行泛型实例之间的属性变化
        ThreeStudent = ThreeStudent.Select(AddTeachersRelationship).ToList();
    }
    
    public static Student AddTeachersRelationship(Student stu)
    {
        var studentAndTeacherRelationship = new List<StudentAndTeacherRelationship>()
        {
            new StudentAndTeacherRelationship("frankie", new List<string>() {"cb", "hongmei"}),
            new StudentAndTeacherRelationship("asan", new List<string>() {"xuyuncong", "fanguangyu"}),
            new StudentAndTeacherRelationship("Qin", new List<string>() {"liusanming", "xuyuncong"})
        };
        foreach (var item in studentAndTeacherRelationship)
        {
            if (stu.Name.Equals(item.StudentName))
            {
                stu.Teachers = item.Teachers;
            }
        }
        return stu;
    }

    三、结果

  • 相关阅读:
    对于Spring中AOP,DI,IoC概念的理解
    Java多线程(2)线程锁
    JVM中ClassLoader的学习
    用心对待博客,用脚对待cv
    硬核关闭wps for linux的自动备份功能
    [翻译]官网文档,ubuntu使用vscode调试c++
    一文快速入门Shell脚本_了解Shell脚本基本命令
    Ubuntu安装旧版本/指定版本的JDK
    ubuntu1204搭建Andriod4.0环境时了解的相关扩展信息
    避免火狐浏览器产生巨大的磁盘写入量及一些小优化
  • 原文地址:https://www.cnblogs.com/YaoFrankie/p/9860300.html
Copyright © 2011-2022 走看看