首页 > 解决方案 > 使用泛型将具有相同属性的 A 类和 B 类的泛型列表转换为 C 类的列表

问题描述

我有 3 个类,DOb、Patient 和 LookUp

public class Dog
    {  public int Id { get; set; }
        public DateTime DOB { get; set; }
        public string FirstName { get; set; }
        public string Display { get; set; }
        public int qqQMS { get; set; }
        public string Description { get; set; }
    }

public class Patient
    {
       public int Id { get; set; }
        public Guid Patid { get; set; }
        public string FirstName { get; set; }
        public string Display { get; set; }
        public string Description { get; set; }
    }
 public class LookUp : ILookUp
        public int Id { get; set; }
        public string Display { get; set; }
        public string Description { get; set; }
    }

我正在尝试轻松获取列表或列表将其转换为列表我之前问过这个问题但从未弄清楚,如果不使用动态,我宁愿在没有动态的情况下使用更流畅的方式

我努力了

 List<LookUp> Look = doggy.Cast<LookUp>().ToList();

  List<LookUp> patLook = pat.Cast<LookUp>().ToList();

也试过这个,但我不满意

public static IList<LookUp> ToLookUp<T>( IEnumerable<T> source)  
        {
            List<LookUp> list = (from prop in source
                                 select new LookUp
                                 {
                                     Display = prop.Display ?? "",
                                     Description = prop.Description ?? "",
                                     Id = prop.Id
                                 }).ToList();
            return list;
        }

扩展方法可以工作

标签: c#listgenericstypes

解决方案


您将需要在您的类上实现接口,此时不需要具体Lookup

public class Dog : ILookUp { ... }

public class Patient : ILookUp { ... }

这样你就可以投射到你的界面并使用它:

var listOfDogs = new List<dog>();

var LookupList = listOfDogs.Cast<ILookup>();

我很乐意,但 Dob 广告患者是在其他地方创建的,我无法修改它们

然后没有更简单的方法可以做到这一点,没有反射就无法真正制作通用解决方案,您将不得不按照您的操作进行投影Lookup,或者为每种类型制作一个表达式。


推荐阅读