How to make list with unique values with dictionary (multiton pattern)

344 Views Asked by At

I need to make this magazine_list that holds only unique values and do it by using dictionary and multiton pattern.
List cannot have two objects with the same both name and price.
I found only one example of multiton pattern in c# and it didn't solve my problem.

It's simplified version of code that I already have, but these are the most important things of that problem.

public class Product
{
  string name;
  int price;
}

public class Coffee : Product 
{
    public Coffee(string _name, int _price)
    {
      name = _name;
      price = _price;
    }
}

public class Tea : Product 
{
    public Tea(string _name, int _price)
    {
      name = _name;
      price = _price;
    }
}

public class Magazine
{
    List<Product> magazine_list;

    public Magazine()
    {
      List<Product> magazine_list = new List<Product>();
    }

    public void add(Product p)
    {
      magazine_list.Add(p);
    }

}
2

There are 2 best solutions below

2
On

Why not make Magazine a dictionary, with the key being product name.

public class Magazine : Dictionary<string, Product>
{
   public void Add(Product p)
   {
      base[p.name] = p;
   }
}
2
On

What you could use is a self-defined class that contains a string identifier and a hashset. The hashset by default will ensure uniqueness.