如何通过整数索引引用 Dictionary<string, string> 中的项?

10

我创建了一个 Dictionary<string, string> 集合,以便可以通过它们的字符串标识符快速引用项目。

但是我现在还需要通过索引计数器 访问这个集合(在实际示例中,foreach无法使用)。

我需要如何修改以下集合,才能够通过整数索引访问其项?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestDict92929
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, string> events = new Dictionary<string, string>();

            events.Add("first", "this is the first one");
            events.Add("second", "this is the second one");
            events.Add("third", "this is the third one");

            string description = events["second"];
            Console.WriteLine(description);

            string description = events[1]; //error
            Console.WriteLine(description);
        }
    }
}
5个回答

15
你无法做到。而你的问题暗示了你认为Dictionary<TKey, TValue>是有序列表,但实际上它不是有序的。如果你需要一个有序的字典,那么这个类型并不适合你。
也许OrderedDictionary会对你有帮助。它提供整数索引。

5

无法做到。正如之前所说,字典没有顺序。

创建一个自己的容器,暴露 IListIDictionary 接口,并在内部管理两个(列表和字典)。这是我在这种情况下所做的。因此,我可以使用两种方法。

基本上

class MyOwnContainer : IList, IDictionary

然后在内部处理

IList _list = xxx
IDictionary _dictionary = xxx

然后在添加/删除/更改中...同时更新。

3
你可以使用System.Collections.ObjectModel命名空间中的KeyedCollection<TKey, TItem>类来实现此功能。只有一个注意点:它是抽象类。因此,你需要继承它并创建自己的类。否则,你可以使用非泛型的OrderedDictionary类。

2

你不能使用索引,因为字典是无序的——在枚举时返回项目的顺序可能随着添加和删除项目而改变。如果要这样做,你需要将项目复制到列表中。


2

Dictionary没有排序,因此索引号是没有意义的。


你的想法是反过来的。把它看作是一个主要是List但具有像Insert、Remove、IndexOf这样的方法 - 但不仅仅是通过整数索引器添加项目和检索,还可以通过其他方式访问它们 - 通常是字符串。DataTable中的DataRow类就是这样运作的。 - mattmc3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接