HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

DuplicateDictionary - A dictionary-like class which allows duplicates

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
allowslikeduplicatedictionarywhichdictionaryclassduplicates

Problem

Since I couldn't find any good answers I made my own class called DuplicateDictionary for personal usage. I would like some tips to improve it.

public class DuplicateDictionary: List>
{
    public DuplicateDictionary()
    {

    }

    public DuplicateDictionary(List> list)
    {
        foreach(KeyValuePair kvp in list)
        {
            this.Add(kvp);
        }
    }

    public DuplicateDictionary(Dictionary dictionary)
    {
        foreach(KeyValuePair kvp in dictionary)
        {
            this.Add(kvp);
        }
    }

    public TValue this[TKey index]
    {
        get
        {
            this.ContainsKey(index);
            return this[index];
        }
        set
        {
            this[index] = value;
        }
    }

    public void Add(TKey key, TValue value)
    {
        this.Add(new KeyValuePair(key, value));
    }

    public bool ContainsKey(TKey key)
    {
        foreach(KeyValuePair kvp in this)
            if(kvp.Key.Equals(key)) return true;

        return false;
    }
}


This class is useful for log things. I use it to log a calculator's past functions and numbers, and once equals is pressed, adds all the past numbers with the functions.

Solution

Such a data structure already exists, and is called ILookup. It can be created using the ToLookup extension.


The ToLookup(IEnumerable, Func) method returns a Lookup, a one-to-many dictionary that maps keys to collections of values. A Lookup differs from a Dictionary, which performs a one-to-one mapping of keys to single values.

var list = new List>
{
    Tuple.Create("a", 1),
    Tuple.Create("a", 2),
    Tuple.Create("a", 3),
    Tuple.Create("b", 4),
    Tuple.Create("c", 5)
};

var lookup = list.ToLookup(t => t.Item1, t => t.Item2);

foreach(var kv in lookup)
{
    Console.Write(kv.Key);
    Console.WriteLine(" - " + string.Join(", ", kv));
}

// prints
// a - 1, 2, 3
// b - 4
// c - 5


As Vince pointed out, your DuplicateDictionary will suffer from slow access. Lookup won't.

Code Snippets

var list = new List<Tuple<string, int>>
{
    Tuple.Create("a", 1),
    Tuple.Create("a", 2),
    Tuple.Create("a", 3),
    Tuple.Create("b", 4),
    Tuple.Create("c", 5)
};

var lookup = list.ToLookup(t => t.Item1, t => t.Item2);

foreach(var kv in lookup)
{
    Console.Write(kv.Key);
    Console.WriteLine(" - " + string.Join(", ", kv));
}

// prints
// a - 1, 2, 3
// b - 4
// c - 5

Context

StackExchange Code Review Q#102026, answer score: 15

Revisions (0)

No revisions yet.