代码之家  ›  专栏  ›  技术社区  ›  Edward Tanguay

如何按整数索引引用字典<string,string>中的项?

  •  10
  • Edward Tanguay  · 技术社区  · 15 年前

    我做了一个 词典 <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 年前
        1
  •  15
  •   Andrew Arnott    15 年前

    你不能。你的问题表明你相信 Dictionary<TKey, TValue> 是一个有序的列表。不是这样。如果你需要一本有序的词典,这种词典不适合你。

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

        2
  •  5
  •   Michał Powaga Mohamed Aslam    11 年前

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

    自己做一个容器 IList IDictionary …内部管理(列表和字典)。在那些情况下我就是这么做的。所以,我可以用这两种方法。

    基本上

    class MyOwnContainer : IList, IDictionary
    

    然后在内部

    IList _list = xxx
    IDictionary _dictionary = xxx
    

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

        3
  •  3
  •   Steven    15 年前

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

        4
  •  2
  •   to StackOverflow    15 年前

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

        5
  •  2
  •   David Pfeffer    15 年前

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