简体   繁体   中英

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 !

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);

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;
     }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM