Fran Martinez
Fran Martinez

Reputation: 679

How add dynamically a list form one object to another?

I have a class that contains a list. I want to copy that list to another object that contains the same type and amount of attributes.

        List<CinemaUnitSchema> cinemaUnitSchemas = new List<CinemaUnitSchema>();
        foreach (CinemaUnit cinemaUnits in scenario.CinemaUnits)
        {
            cinemaUnitSchemas.Add(new CinemaUnitSchema
            {
                Name = cinemaUnits.Name,
                AttendantPoints = cinemaUnits.AttendantPoints,
                ShowPoints = cinemaUnits.ShowPoints
            });                

        }
        scenarioSchema.CinemaUnits.AddRange(CinemaUnitSchemas);

However, I'm receiving an error in this line of code;

AttendantPoints = cinemaUnits.AttendantPoints

The error I'm receiving is:

"Cannot implicitly convert type 'System.Collections.Generic.List < MyApp.Models.AttendantPoint >' to 'System.Collections.Generic.List < MyApp.Schemas.AttendantPointSchema >'."

Class of CinemaUnit is:

public class CinemaUnit
{
    public string Name { get; set; }    
    public List<AttendantPoint> AttendantPoints { get; set; }
    public bool ShowPoints { get; set; }
}

The Class of CinemaUnitSchema is:

public class CinemaUnitSchema
{
    public string Name { get; set; }    
    public List<AttendantPoint> AttendantPoints { get; set; }
    public bool ShowPoints { get; set; }
}

Solution Intended

Add in each iteration the respective list to the new object.

Thanks,

Upvotes: 0

Views: 154

Answers (3)

R. Roe
R. Roe

Reputation: 609

Not sure if this is the problem, but it is probably a good bet that it is. You are using a foreach statement with the camel case cinemaUnits but when you are trying to copy the fields you are using the title case CinemaUnits instead of the variable with camel case.

Upvotes: 0

Valerii
Valerii

Reputation: 2317

What you actually need it's a way to convert AttendantPoint to AttendantPointSchema.

Solution 1: You can use AutoMapper framework to do it.

Solution 2: You can write generic converter like @Eser suggested.

Solution 3: You can crate converter manually for each class using extension methods, implicit or explicit operators or just write helper class with static functions.

Upvotes: 0

Eser
Eser

Reputation: 12546

You can write a Copy method that makes a shallow copy using reflection.

void Copy(object from, object to)
{
    var dict = to.GetType().GetProperties().ToDictionary(p => p.Name, p => p);
    foreach(var p in from.GetType().GetProperties())
    {
        dict[p.Name].SetValue(to, p.GetValue(from,null), null);
    }
}

Upvotes: 2

Related Questions