在 C# 中,我可以有一个接受不同数据类型的值的哈希表。但我想要一个可以维护插入顺序的数据结构。
我是从 Java 背景转向 C# 的,我想知道解决它的干净方法。我不想要 Hashtable 的 O(1) 查找复杂度。
这是我的哈希表的样子。
public void foo() {
List<string> mylist1 = new List<string>(new string[] { "1", "2", "3" });
List<int> mylist2 = new List<int>(new int[] { 1, 2, 3 });
Hashtable hashTable = new Hashtable();
hashTable.Add("1", "One");
hashTable.Add("2", 2);
hashTable.Add("3", mylist1);
hashTable.Add("4", mylist2);
foreach(string key in hashTable.Keys)
{
Console.WriteLine(String.Format("{0}: {1}", key, hashTable[key]));
}
}
如果我想保持插入顺序,List 似乎是正确的数据结构。我正在考虑 new List>
。但我的值可以是任何数据类型。
因此,我正在寻找一种可以维护插入顺序并允许值使用不同数据类型的数据结构(如哈希表)。我怎样才能在 C# 中实现这一目标?
我应该使用 保留顺序的字典数据结构吗?
In C#, I can have a Hashtable that accepts different data types for the values. But I want a datastructure that can maintain the insertion order.
I am coming to C# from Java background and I would like to know a clean way of solving it. I don't want the O(1) lookup complexity of an Hashtable.
Here is how my Hashtable would be.
public void foo() {
List<string> mylist1 = new List<string>(new string[] { "1", "2", "3" });
List<int> mylist2 = new List<int>(new int[] { 1, 2, 3 });
Hashtable hashTable = new Hashtable();
hashTable.Add("1", "One");
hashTable.Add("2", 2);
hashTable.Add("3", mylist1);
hashTable.Add("4", mylist2);
foreach(string key in hashTable.Keys)
{
Console.WriteLine(String.Format("{0}: {1}", key, hashTable[key]));
}
}
If I want to maintain the insertion order, List seems to be the right data structure. I am thinking of new List<Tuple<string, var>>
. But my values can be of any data type.
So I am looking for a data structure that can maintain insertion order and allow different datatypes for the values (like an Hashtable). How can I achieve this in C#?
Should I use a dictionary data structure that preserves the order instead?
发布评论