Hypothetical example: I have a list of customers and a list of products in memory. I want to be able to access the products that each customer has bought as well as the customers who bought a specific product:
class Customer
{
public List<Product> Products { get; set; }
}
class Product
{
public List<Customer> CustomersWhoBoughtThis { get; set; }
}
var customers = new List<Customer>();
var products = new List<Product>();
//add the customers
var customer1 = new Customer();
customers.Add(customer1);
var customer2 = new Customer();
customers.Add(customer2);
//add the products
var product1 = new Product();
products.Add(product1);
var product2 = new Product();
products.Add(product2);
//add a purchased product for customer1
customer1.Products.Add(product1);
//How do I get customer1 from product1?
foreach (var customerWhoBoughtProduct1 in product1.CustomersWhoBoughtThis)
{
//do something
}
I could just manually add the customer to the product's CustomersWhoBoughtThis
list, but I feel like this is prone to errors since you may forget to do it somewhere.
Is there a better implementation to this? Maybe some sort of wrapper class that handles the functionality, but I'm not sure how it would be implemented. Any advice?
Thanks