MVC C #: use la misma lista de objetos en diferentes modelos (¿referencia?)

I want to use the same list of object in different models. The MainModel should take care about the content of the list so the SubModels using that list get the change as well.

Given following Model 'Customer'...

public class Customer
{
    public Customer(List<Customer> customerList)
    {
        this.CustomerList= customerList;
        this.CustomerAge= new CustomerAge(this.CustomerList);
    }

    public List<Customer> CustomerList
    {
        get;
        set;
    }

    public AgeCustomer AgeCustomer
    {
        get;
        set;
    }

    public void SetCustomerList(List<Customer> customerList)
    {
        this.CustomerList= customerList;
    }
}

Y el modelo CustomerAge:

public class CustomerAge
{
    List<Customer> customerListComplete;

    public CustomerAge(List<Customer> customerList)
    {
        this.customerListComplete= customerList;

    }

    public List<Customer> CustomerListAgeOver40
    {
        get
        {
            return this.customerListComplete.Where(c => c.age > 40).ToList();
        }
    }

    public List<Customer> CustomerListAgeUnder40
    {
        get
        {
            return this.customerListComplete.Where(c => c.age < 40).ToList();
        }
    }

    public List<Customer> CustomerListAgeEquals40
    {
        get
        {
            return this.customerListComplete.Where(c => c.age = 40).ToList();
        }
    }
}

Pretty simple so far, I have a main model called Customer and a helper model called CustomerAge. Cuando cambio el CustomerList in Customer al Customer.SetCustomerList(newCustomerList), I thought that the CustomerListComplete in CustomerAge would change as well, but it dosen't. Why? How can I use the same list in both of models?

preguntado el 09 de marzo de 12 a las 13:03

1 Respuestas

This is because your collection is referenced by, well, references.

CustomerList in Customer y customerListComplete in CustomerAge are just 'pointers' to a collection. When you changes CustomerList, customerListComplete no cambia

Necesitas agregar public void SetCustomerList(List<Customer> customerList) a CustomerAge y llámalo desde Customer.SetCustomerList.

Other solution is to change CustomerAge constructor to get the instance of Customer Y luego usar Customer.CustomerList:

public Customer(List<Customer> customerList)
{
    this.CustomerList= customerList;
    this.CustomerAge= new CustomerAge(this);
}

respondido 09 mar '12, 13:03

Thanks, I took the second solution. I think, one more solution would be to change SetCustomerList(): this.CustomerList.Clear() y entonces this.CustomerList.AddRange(customerList) so I don't change the reference but the content of the reference. Am I right? - iappwebdev

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.