avnic
avnic

Reputation: 3361

c# merge objects

    Class Person
    {
        string Name
        int yesno
        int Change
        List<Cars> Personcars;
        houses Personhouses
    }

Person user1 = new Person()
Person user2 = new Person()

user1.Name = "userName"
user2.Name ="";

user2.cars[0] = new car("Mazda");
user1.cars[0] = new car("BMW");

i want to merge the objects so that user2 will take the name and the car from user1

user2 will have this values

user2.Name will be userName user2.cars will hold the Mazda and the Bmw

thanks !

Upvotes: 2

Views: 957

Answers (2)

hunter
hunter

Reputation: 63562

user2.Name = user1.Name;
user2.Personcars.AddRange(user1.Personcars);

You could add this as a method on the class itself:

public class Person
{
    List<Cars> _personcars;

    public string Name { get; set; }
    // what the hell is a yesno int? If it's 1 or 0 then just use a bool
    public int yesno { get; set; }
    public int Change { get; set; }
    public List<Cars> Personcars 
    {
        get
        {
            return _personcars ?? (_personCars = new List<Cars>());
        }
        set { _personcars = value; }
    }
    public Houses Personhouses { get; set; }

    public void Merge(Person person)
    {
        Name = person.Name;
        Personcars.AddRange(person.Personcars);
    }
}

Which will allow you to write something like this:

user2.Merge(user1);

Upvotes: 3

Amir Ismail
Amir Ismail

Reputation: 3883

Try this extension methods

 public void Merge(this Person _person, Person source)
 {
     _person.Name = source.Name;
     if(_person.Cars !=null)
     {
        _person.Cars.AddRang(source.Cars);
     }
     else
     {
        _person.Cars = source.Cars;
     }
 }

Upvotes: 3

Related Questions