c# - 使用泛型将具有相同属性的 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;
}
扩展方法可以工作
解决方案
您将需要在您的类上实现接口,此时不需要具体类:Lookup
public class Dog : ILookUp { ... }
public class Patient : ILookUp { ... }
这样你就可以投射到你的界面并使用它:
var listOfDogs = new List<dog>();
var LookupList = listOfDogs.Cast<ILookup>();
我很乐意,但 Dob 广告患者是在其他地方创建的,我无法修改它们
然后没有更简单的方法可以做到这一点,没有反射就无法真正制作通用解决方案,您将不得不按照您的操作进行投影Lookup
,或者为每种类型制作一个表达式。
推荐阅读
- python - 不要为单个函数记录警告
- c# - 当组件未显示时如何修复设计器?
- ruby-on-rails - 如何修复未使用 service worker 和 onesignal 定义的 importScripts?
- r - 在R中将一列一分为二
- php - PHP取消嵌套多维数组中的所有元素
- c++ - 错误:“shuffle”不是“std”的成员
- node.js - botframework v4:使用 botframework 模拟器触发 onEvent 方法
- vb.net - 试图将我的 vb.net 2019 连接到 access2010
- php - Laravel 更新后无法找到 ClientObserver
- linux - 在 Linux Mint 上安装 Azure CLI 时出错?