【问题标题】:How to refer to items in Dictionary<string, string> by integer index?如何通过整数索引引用 Dictionary<string, string> 中的项目?
【发布时间】:2011-01-25 00:42:38
【问题描述】:

我创建了一个 Dictionary&lt;string, string&gt; 集合,以便我可以通过它们的字符串标识符快速引用这些项目。

但我现在还需要通过 index counter访问这个集合(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);
        }
    }
}

【问题讨论】:

    标签: c# dictionary indexing


    【解决方案1】:

    你不能。您的问题推断出您认为Dictionary&lt;TKey, TValue&gt; 是一个有序列表。它不是。如果您需要有序字典,则此类型不适合您。

    也许OrderedDictionary 是你的朋友。它提供整数索引。

    【讨论】:

      【解决方案2】:

      你不能。如前所述 - 字典没有顺序。

      制作您的 OWN CONTAINER,公开 IListIDictionary... 并在内部管理这两者(列表和字典)。这就是我在这些情况下所做的。所以,我可以同时使用这两种方法。

      基本上

      class MyOwnContainer : IList, IDictionary
      

      然后是内部

      IList _list = xxx
      IDictionary _dictionary = xxx
      

      然后在添加/删除/更改...更新两者。

      【讨论】:

        【解决方案3】:

        您可以为此使用System.Collections.ObjectModel 命名空间中的KeyedCollection&lt;TKey, TItem&gt; 类。只有一个问题:它是抽象的。所以你必须继承它并创建你自己的:-)。否则使用非泛型 OrderedDictionary 类。

        【讨论】:

          【解决方案4】:

          您不能:索引没有意义,因为字典没有排序 - 枚举时返回项目的顺序可能会随着您添加和删除项目而改变。您需要将项目复制到列表中才能执行此操作。

          【讨论】:

            【解决方案5】:

            Dictionary 未排序/排序,因此索引号将毫无意义。

            【讨论】:

            • 你在想它。将其视为主要是List,但使用诸如 Insert、Remove、IndexOf 之类的方法 - 但不仅仅是通过整数索引器添加项目和检索,您还可以通过其他方式获取它们 - 通常是字符串。 DataTable 中的DataRow 类的功能有点像这样。
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2010-12-03
            • 1970-01-01
            • 1970-01-01
            • 2012-03-01
            • 1970-01-01
            • 2014-10-22
            • 1970-01-01
            相关资源
            最近更新 更多