两个泛型实例之间的属性变化
两个泛型实例之间的属性变化,需要借助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; }
三、结果