Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# equivalent of LinkedHashMap [duplicate]

As the question says, I'm looking for the c# equivalent of the LinkedHashMap in Java.

I need to be able to retrieve keys and values by index, get the size. I need the elements to be ordered in the way they are inserted. One key should be matched to exactly one value.

Collections I've tried (And problems with them):
NameValueCollection - Allows one-many linking. I'm guessing this causes an unnecessary overhead.
OrderedDictionary - Unable to retrieve key by index.

EDIT : It has been pointed out that no such equivalent exists in C#. In the linked question, the answer points to a forum for an example implementation, which appears to be down. Could someone perhaps provide an example implementation here?

EDIT 2 : A CookieCollection from System.Net appears to be what I need. How would this react to larger sizes (number of elements)?

like image 235
Hele Avatar asked Mar 23 '15 08:03

Hele


Video Answer


1 Answers

I wrote this one, worked well enough for me in the past. Let me know if you find a mistake.

using System;
using System.Collections.Generic;

class LinkedHashMap<T, U>
{
    Dictionary<T, LinkedListNode<Tuple<U, T>>> D = new Dictionary<T, LinkedListNode<Tuple<U, T>>>();
    LinkedList<Tuple<U,T>> LL = new LinkedList<Tuple<U, T>>();

    public U this[T c]
    {
        get
        {
            return D[c].Value.Item1;
        }

        set
        {
            if(D.ContainsKey(c))
            {
                LL.Remove(D[c]);
            }

            D[c] = new LinkedListNode<Tuple<U, T>>(Tuple.Create(value, c));
            LL.AddLast(D[c]);
        }
    }

    public bool ContainsKey(T k)
    {
        return D.ContainsKey(k);
    }

    public U PopFirst()
    {
        var node = LL.First;
        LL.Remove(node);
        D.Remove(node.Value.Item2);
        return node.Value.Item1;
    }

    public int Count
    {
        get
        {
            return D.Count;
        }
    }
}

class LinkedHashMapTest 
{
    public static void Test()
    {
        var lhm = new LinkedHashMap<char, int>();

        lhm['a'] = 1;
        lhm['b'] = 2;
        lhm['c'] = 3;


        Console.WriteLine(lhm['a']);
        Console.WriteLine(lhm['b']);
        Console.WriteLine(lhm['c']);

        Console.WriteLine(lhm.PopFirst());
        Console.WriteLine(lhm.PopFirst());
        Console.WriteLine(lhm.PopFirst());
    }
}
like image 83
N0thing Avatar answered Oct 18 '22 21:10

N0thing