C# 接受不同数据类型并保持插入顺序的数据结构

发布于 2025-01-09 19:28:52 字数 965 浏览 2 评论 0 原文

在 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文