可通过索引和密钥访问的内置列表

是否可以创建一个可以通过索引或密钥访问的列表?

我正在寻找已经存在但具有此function的Collection类型,我想避免重新定义索引器

System.Collections.Specialized.NameValueCollection可以执行此操作,但它只能将字符串存储为值。

System.Collections.Specialized.NameValueCollection k = new System.Collections.Specialized.NameValueCollection(); k.Add("B", "Brown"); k.Add("G", "Green"); Console.WriteLine(k[0]); // Writes Brown Console.WriteLine(k["G"]); // Writes Green 

现有答案已经显示了如何添加自己的索引器。

您可能希望查看一些现有的基于键的集合,例如SortedList<,> ,其行为类似于Dictionary<,> ,但允许键和位置索引器使用。

此外 – 您应该能够inheritance大部分类型的东西 – 例如,inheritanceCollection<>List<> 。 请注意,如果您的集合实现IList / IList ,我不推荐以下(我偶尔会看到):

 public SomeType this[int someId] {...} 

关键是,人们期望IList[]的整数索引器是位置的。

有一个类似的问题是什么是.NET中用于通过字符串键或数字索引查找的最佳数据结构? 。

看看KeyedCollection :

 class IndexableDictionary : KeyedCollection { Dictionary keys = new Dictionary(); protected override TKey GetKeyForItem(TItem item) { return keys[item];} public void Add(TKey key, TItem item) { keys[item] = key; this.Add(item); } } 
 public object this[int index] { get { ... } set { ... } } 

除了只做一个整数索引,你可以提供你喜欢的任何其他类型的键

 public object this[String key] { get { ... } set { ... } } 

如果您不想定义自己的集合,只需inheritanceList ,或者只使用List类型的变量。

您可以通过将以下属性添加到集合来添加索引器:

 public object this[int index] { get { /* return the specified index here */ } set { /* set the specified index to value here */ } } 

可以通过键入索引器并按[tab] [tab]在Visual Studio中快速添加。

返回类型和索引器类型可以改变。 您还可以添加多个索引器类型。