Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy/Clone all values from a List to another in a C#

Tags:

c#

clone

list

I have a class

public class Car()
{
    public string Name;
    public string Model;
}

And i have a property

List<Car> CarsA = new List<Car>();
CarsA.Add(new Car(){Name = "Verna",Model="Hyundai"});
CarsA.Add(new Car(){Name = "X1",Model="Bmw"});

and i have another property

List<Car> CarsB = new List<Car>();

Now i want to add clone/copy all the entries from CarsA to CarsB without taking CarsA properties current instances

(i.e. i want to create new object for each entry and add it).

Something like

foreach(var car in CarsA)
{
    Car newCar =new Car();
    newCar.Name = car.Name;
    newCar.Model = car.Model;
    CarsB.Add(newCar);
}

What if i don't want to implement ICloneable and i don't have a copy contructor?

like image 695
Vivek Saurav Avatar asked Jan 28 '16 14:01

Vivek Saurav


1 Answers

You could probably consider LINQ solution:

List<Car> CarsB = (from c in CarsA
                    let a = new Car() { Name = c.Name, Model = c.Model }
                    select a).ToList();

Since Name and Model are of string type (which is immutable), this operation is safe.

It is quite readable, I think.

Same but with query syntax:

CarsB = CarsA.Select(c => new Car(){ Name = c.Name, Model = c.Model }).ToList();

Note: If, suppose, the Model is not string but a class, then the operation above a = new Car() must be slightly change to something which really clone all the items in the model (something like this: Model = c.Model.Clone()) and not just referring to it (Model = c.Model)

like image 53
Ian Avatar answered Oct 06 '22 00:10

Ian