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;
}
}
And the Model 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. When I change the CustomerList in Customer by calling 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?
This is because your collection is referenced by, well, references.
CustomerListinCustomerandcustomerListCompleteinCustomerAgeare just ‘pointers’ to a collection. When you changesCustomerList,customerListCompletedoesn’t change.You need to add
public void SetCustomerList(List<Customer> customerList)toCustomerAgeand call it fromCustomer.SetCustomerList.Other solution is to change
CustomerAgeconstructor to get the instance ofCustomerand then useCustomer.CustomerList: