C#相当于LinkedHashMap中的 [英] C# equivalent of LinkedHashMap

查看:297
本文介绍了C#相当于LinkedHashMap中的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于这个问题说,我找的C#相当于在的LinkedHashMap 在Java中。

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.

收藏我试过(和问题,与他们):结果
的NameValueCollection - 允许一对多链接。我猜这会导致不必要的开销,结果
OrderedDictionary - 。无法检索索引键

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.

修改:有人指出,没有同样的在C#中存在。在链接的问题,回答指向一个示例实现中,这似乎是向下的论坛。 ?可能有人也许这里提供一个例子实施

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?

编辑2 :A CookieCollection 从System.Net似乎是我需要的。这将如何应对大尺寸(元素数目)?

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

推荐答案

我写了这一块,已经足够好了,我在过去。 。让我知道,如果你发现一个错误

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());
    }
}

这篇关于C#相当于LinkedHashMap中的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆