[英]Combine Two Entities Into One Using LINQ
I am trying to combine my two different entities into one new entity. 我正在尝试将两个不同的实体合并为一个新实体。 Here is a sample of my class entity: 这是我的班级实体的一个示例:
public class CarOne
{
public string Name { get; set; }
public string Model { get; set; }
}
public class CarTwo
{
public int Year { get; set; }
public string Description { get; set; }
}
Now I want to save all my list of two enties into this new entity: 现在,我要将所有两个实体的列表保存到这个新实体中:
public class CarFinal
{
public string Name { get; set; }
public string Model { get; set; }
public int Year { get; set; }
public string Description { get; set; }
}
Here is the sample of my code: 这是我的代码示例:
CarOne carToyota = new CarOne()
{
Name = "Toyota",
Model = "Camry"
};
CarTwo carDetails = new CarTwo()
{
Year = 2012,
Description = "This is a great car"
};
List<CarOne> lstFirst = new List<CarOne>();
lstFirst.Add(carToyota);
List<CarTwo> lstSecond = new List<CarTwo>();
lstSecond.Add(carDetails);
Now here is what I am trying to do, I am trying to combine these two list which contains same number of elements, in this case, both List contains one number of element. 现在这是我要执行的操作,我试图将这两个包含相同数量元素的列表组合在一起,在这种情况下,两个列表都包含一个元素数量。 What I have tried so far is: 到目前为止,我尝试过的是:
var result1 = lstFirst.Select(x => new CarFinal
{
Name = x.Name,
Model = x.Model
}).ToList();
var result2 = lstSecond.Select(x => new CarFinal
{
Year = x.Year,
Description = x.Description
}).ToList();
List<CarFinal> lstFinal = new List<CarFinal>();
lstFinal = result1.Union(result2).ToList();
I also tried: 我也尝试过:
lstFinal = result1.Concat(result2).ToList();
But the output of these two methods will both produce two elements, which is I am trying to just combine all properties into one. 但是这两种方法的输出都将产生两个元素,这是我试图将所有属性组合为一个元素。 I am expecting one entity only as result but I am always getting two elements on my combination. 我只希望得到一个实体,但是我总是在组合中得到两个要素。
Use Zip
like this: 像这样使用Zip
:
var finalList = lstFirst.Zip(lstSecond, (c1, c2) => new CarFinal()
{
Name = c1.Name,
Model = c1.Model,
Description = c2.Description,
Year = c2.Year
}).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.