2010-03-08 66 views
10

我发了一个词典<string, string>收集,以便我可以通过他们的字符串标识快速参考项目。如何通过整数索引引用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); 
     } 
    } 
} 

回答

15

你不能。而你的问题推断你的信念Dictionary<TKey, TValue>是一个有序列表。不是这样。如果你需要一个有序的字典,这种类型不适合你。

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

+1

到底我在找什么,谢谢 – 2010-03-08 15:33:56

2

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

2

Dictionary没有排序/排序,所以索引号将是没有意义的。

+0

你在想它。可以认为它主要是一个'List',但是可以使用像Insert,Remove,IndexOf这样的方法 - 但不是通过一个整数索引器添加项目和检索,而是通过其他方式 - 通常是一个字符串。 DataTable中的DataRow类就像这样。 – mattmc3 2010-07-12 20:15:54

5

你不行。正如所说 - 字典没有秩序。

让您的自己的容器,公开IListIDictionary ...并在内部管理(列表和字典)。这是我在这些情况下所做的。所以,我可以使用这两种方法。

基本上

class MyOwnContainer : IList, IDictionary 

,然后在内部

IList _list = xxx 
IDictionary _dictionary = xxx 

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

3

您可以在System.Collections.ObjectModel命名空间中为此使用KeyedCollection<TKey, TItem>类。只有一个问题:它是抽象的。所以你将不得不从它继承并创建你自己的:-)。否则使用非通用的OrderedDictionary类。

+1

用于KeyedCollection – 2010-03-08 15:27:05