【问题标题】:Combine Two Entities Into One Using LINQ使用 LINQ 将两个实体合二为一
【发布时间】:2017-02-26 15:40:12
【问题描述】:

我正在尝试将我的两个不同实体合并为一个新实体。这是我的类实体的示例:

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; }  

    }

现在我想将我所有的两个实体列表保存到这个新实体中:

public class CarFinal
    {
        public string Name { get; set; }

        public string Model { get; set; }

        public int Year { get; set; }

        public string Description { get; set; }  

    }

这是我的代码示例:

        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);

现在这是我想要做的,我试图将这两个包含相同数量元素的列表组合起来,在这种情况下,两个列表都包含一个元素数量。到目前为止我尝试过的是:

        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();

我也试过了:

        lstFinal = result1.Concat(result2).ToList();

但是这两种方法的输出都会产生两个元素,这是我试图将所有属性组合成一个元素。我只期望一个实体作为结果,但我总是在我的组合中得到两个元素。

【问题讨论】:

  • 在使用方法前请先了解方法!

标签: c# linq linq-to-entities


【解决方案1】:

像这样使用Zip

var finalList = lstFirst.Zip(lstSecond, (c1, c2) => new CarFinal()
        {
            Name = c1.Name,
            Model = c1.Model,
            Description = c2.Description,
            Year = c2.Year
        }).ToList();

【讨论】:

    猜你喜欢
    • 2021-06-02
    • 2015-01-20
    • 1970-01-01
    • 2015-12-30
    • 2019-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多