How can you design a collection that can accept duplicate keys?

By design, a Dictionary requires the key element to be unique and doesn't allow duplicate keys. To design a data structure that can hold key-value pairs with a possible duplicate keys, we can go with one of the following:

  1. A List of KeyValue Pairs - we maintain a List of KeyValue pairs and since a List doesn't have a key concept, we can still store key values for duplicate keys.
var a = new List<KeyValuePair<char, C>>();
a.Add(new KeyValuePair<char, C>('c', new C
{
    Id = 1001,
    Name = "Diippop",
    AddedOn = DateTime.Now
}));
  1. A Dictionary that stores a collection - we can push the values that come in for a key into a collection and still maintain a unique key.
var d= new Dictionary<char, List<C>>();
d.Add('c', new List<C>());
d['c'].Add(new C
{
    Id = 1001,
    Name = "Diippop"
});
  1. A Lookup - a data structure available from the System.Linq namespace which stores a grouping of values for a defined Key. The Lookup can then be looked up for a key with constant time and the value collection can be iterated.
var a = new List<C>()
{
    new C
    {
        Id = 1001,
        Name = "Diippop"
    },
    new C
    {
        Id = 1002,
        Name = "Diippop"
    }
};
var lookup = a.ToLookup(x => x.Name.Substring(0, 1), x => x.Id);
foreach (var e in lookup)
{
    Console.WriteLine($"Key: {e.Key}");
    foreach (var k in e)
    {
        Console.WriteLine(k);
    }
}
Output:
Key: D
1001
1002

C# Concepts Posted May 22, 2021

You can now show your support. 😊

We use cookies to provide you with a great user experience, analyze traffic and serve targeted promotions.   Learn More   Accept