2010-03-08 63 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