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

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 a clone / copy all entries from CarsA to CarsB without accepting the current instances of CarsA

(i.e. I want to create a new object for each record and add it).

Sort of

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

What if I do not want to implement ICloneable and I do not have a copy constructor?

+4
source share
3 answers

You can probably consider the LINQ solution:

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

Because Nameand Modelhave a type string(which is constant), the operation is safe.

It is quite readable, I think.

The same, but with the query syntax:

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

. , , Model string, a class, a = new Car() - (- : Model = c.Model.Clone()), (Model = c.Model)

+4

JSON, , , .

, , . , , .

, Json.net , :

public static T Clone<T>(this T source)
{
    if (Object.ReferenceEquals(source, null))
        return default(T);

    return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(source));
}

( ), , , BinaryFormatter: ( , [Serializable])

public static T Clone<T>(this T source)
{
    if (Object.ReferenceEquals(source, null))
        return default(T);

    using (var stream = new MemoryStream())
    {
        var formatter = new BinaryFormatter();
        formatter.Serialize(stream, source);
        stream.Position = 0;

        return (T) formatter.Deserialize(stream);
    }
}

:

foreach(var car in CarsA)
{
    CarsB.Add(car.Clone<Car>());
}

:

List<Car> CarsB = CarsA.Clone<List<Car>>();
+2

Linq

var CarsB = CarsA.Cast<Car>().ToList();

Cast < > ing , , , .., .

0

Source: https://habr.com/ru/post/1626359/


All Articles