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?
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 notstring
but aclass
, then the operation abovea = 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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With