0

I have the following class tructure:

    public class Parent
    {
        public int Property1;
        public int Property2;
        public int Property3;
        //Lots more properties
    }

    public class Child : Parent
    {
        public int Property80;
    }

and a list of parent like this:

var parentList = new List<Parent>
        {
            //Some data....
        };

I now want to make a new list of child that has all the data from parentList

I know I can do this:

var childList = parentList.Select(x => new Child { Property1 = x.Property1, Property2 = x.Property2, //etc }

but my question is, is there a shorthand or one line way of doing this, to save me having to write a huge list of properties out?

Alex
  • 3,730
  • 9
  • 43
  • 94
  • 1
    check this out https://stackoverflow.com/questions/16534253/c-sharp-converting-base-class-to-child-class/25653977, also consider using object-to-object mapping library such as AutoMapper. – Abdulrahman Awwad Nov 24 '19 at 13:54

1 Answers1

1

When you create the Parent list use Child class

var parentList = new List<Parent>
{
    new Child { Property1 = 1, Property2 = 2, Property3 = 3 },
    new Child { Property1 = 4, Property2 = 5, Property3 = 6 },
    new Child { Property1 = 7, Property2 = 8, Property3 = 9 }
};

This is the equivalent of Parent p = new Child { Property1 = 1, Property2 = 2, Property3 = 3 }

Now you can cast it to Child and just add the missing properties in Select

var childList1 = parentList.Select(x => { Child y = (Child)x; y.Property80 = 80; return y; });
Guy
  • 46,488
  • 10
  • 44
  • 88