Copy/Clone all values from a List to another in a C# -
i have class
public class car() { public string name; public string model; }
and have property
list<car> carsa = new list<car>(); carsa.add(new car(){name = "verna",model="hyundai"}); carsa.add(new car(){name = "x1",model="bmw"});
and have property
list<car> carsb = new list<car>();
now want add clone/copy entries carsa carsb without taking carsa properties current instances
(i.e. want create new object each entry , add it).
something
foreach(var car in carsa) { car newcar =new car(); newcar.name = car.name; newcar.model = car.model; carsb.add(newcar); }
what if don't want implement icloneable , don't have copy contructor?
you consider linq solution:
list<car> carsb = (from c in carsa let = new car() { name = c.name, model = c.model } select a).tolist();
since name
, model
of string
type (which immutable), operation safe.
it quite readable, think.
same query syntax:
carsb = carsa.select(c => new car(){ name = c.name, model = c.model }).tolist();
note: if, suppose,
model
notstring
class
, operation abovea = new car()
must change clone items in model (something this:model = c.model.clone()
) , not referring (model = c.model
)
Comments
Post a Comment