Search code examples
c#linqlinq-to-entities

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.


Solution

  • Use Zip like this:

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