![](/img/trans.png)
[英]How to convert a object of one class to another (where the class members are different)
[英]convert a class object into another class object and then combine
假设我有两个模型/类。
public class Male
{
public int RunNumber { get; set; }
public string Notes { get; set; }
public DateTime thing {get ; set;}
}
public class Female
{
public int StopNumber { get; set; }
public string Notes { get; set; }
public DateTime? thing {get;set;}
}
我想要一个List<People>
组合List<Male>
和List<Female>
。 每次看LINQ,我的大脑都不配合。 我认为这是我追求的连续性。
假设你不想太花哨,并且有一个原因,男性和女性有不同的成员(没有双关语)并且不继承共同的父级,创建一个数据传输对象并使用 Select 映射到它。
public class Person
{
public int StopNumber { get; set; }
public string Notes { get; set; }
public DateTime? thing { get; set; }
public bool IsMale { get; set; }
}
public List<Person> Join(List<Male> males, List<Female> females)
{
return
males.Select(
n => new Person() {
IsMale = true,
Notes = n.Notes,
StopNumber = n.RunNumber,
thing = n.thing}
).Concat(
females.Select(
m => new Person() {
IsMale = false,
Notes = m.Notes,
StopNumber = m.StopNumber,
thing = m.thing})
).ToList();
}
但是——如果它们可以继承一个公共的 Person 基类并具有公共的成员名称,那么它会让您的生活变得更加轻松。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.