【问题标题】:Built-in List that can be accessed by index and key可以通过索引和键访问的内置列表
【发布时间】:2010-09-22 20:00:41
【问题描述】:

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

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

【问题讨论】:

  • 定义索引和键。贴出你想写的语法。
  • 当您说“创建”时,您是在寻找使用此功能创建新类型的 Collection,还是在寻找已经存在但具有此功能的 Collection 类型?

标签: c# dictionary list


【解决方案1】:

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

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

另外 - 您应该能够对大部分此类事情使用继承 - 例如,从 Collection<>List<> 继承。请注意,如果您的集合实现了IList/IList<T>,我不推荐以下(我偶尔会看到):

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

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

【讨论】:

    【解决方案2】:

    What is the best data structure in .NET for look-up by string key or numeric index? 也有类似的问题。

    看看KeyedCollection:

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

    【讨论】:

      【解决方案3】:

      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
      

      【讨论】:

        【解决方案4】:
        public object this[int index]
        {
            get { ... }
            set { ... }
        }
        

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

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

        如果您不想定义自己的集合,只需从List&lt;T&gt; 继承,或者只使用List&lt;T&gt; 类型的变量。

        【讨论】:

          【解决方案5】:

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

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

          这可以通过键入 indexer 并按 [tab] [tab] 快速添加到 Visual Studio 中。

          当然可以更改返回类型和索引器类型。您还可以添加多种索引器类型。

          【讨论】:

            猜你喜欢
            • 2021-07-18
            • 2010-09-05
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-05-01
            • 1970-01-01
            • 1970-01-01
            • 2018-05-07
            相关资源
            最近更新 更多