Hel*_*ele 6 c# java collections
正如问题所说,我正在寻找Java中LinkedHashMap的c#等价物.
我需要能够通过索引检索键和值,获取大小.我需要按插入方式排序元素.一个键应该与一个值匹配.
我尝试过的集合(以及它们的问题):
NameValueCollection - 允许一对多链接.我猜这会导致不必要的开销.
OrderedDictionary - 无法通过索引检索密钥.
编辑:有人指出C#中不存在这样的等价物.在链接的问题中,答案指向一个示例实现的论坛,该论坛似乎已关闭.有人可能会提供一个示例实现吗?
编辑2:来自System.Net 的CookieCollection似乎是我需要的.这对较大尺寸(元素数量)有何影响?
我写了这个,过去对我来说效果很好。如果您发现错误,请告诉我。
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());
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7294 次 |
| 最近记录: |