【问题标题】:What type is the best for loose numerically-indexed lists in C#?哪种类型最适合 C# 中松散的数字索引列表?
【发布时间】:2014-02-14 21:02:18
【问题描述】:

我需要的是一个类似数组的东西,但让我可以随时将一个元素分配给任何索引,并检查是否已经有一个值分配给特定索引,类似于

MyArray<string> a = new MyArray<string>();
a[10] = "ten";
bool isTheFifthElementDefined = a[5] != null; // false

也许Dictionary&lt;int, string&gt; 及其ContainsKey 方法可以做到,但如果我想要一个仅包含数字键的有序集合,难道没有更合适的数据结构吗?

我还需要遍历定义的元素(最好使用 foreach 或 linq)访问当前元素的值和键。

【问题讨论】:

  • 你不会得到任何开箱即用的东西,但我在我的一个名为DynamicArray 的项目中创建了类似的东西,这可能对你有用。基本上,它实现了您正在寻找的隐喻:能够在数组中的特定索引处分配一个值,而不管数组(当前)是否真的那么大。
  • ArrayList 也可以使用。
  • SortedDictionary<int,string>?当你说“只有数字键的有序集合”时,你到底想要什么?
  • Perhaps Dictionary&lt;int, string&gt; with its ContainsKey method could do, but isn't there a more appropriate data structure if I want an ordered collection with numeric keys only? - 没有。
  • @Superbest:嗯,实际上,Dictionary&lt;int,string&gt; 没有排序,枚举键可能以任何顺序返回。因此,SortedDictionary&lt;int,string&gt; 在技术上更合适。

标签: c# .net collections types


【解决方案1】:

正如你提到的Dictionary 似乎更适合这个。但是你可以使用通用列表来做到这一点,例如,当你创建你的列表时,你可以指定一个元素计数,你可以给所有的默认临时值你的元素。

List<string> myList = new List<string>(Enumerable.Repeat("",5000));
myList[2300] = "bla bla bla..";

对于int:

List<int> myList = new List<int>(Enumerable.Repeat(0,5000));

对于custom type

List<MyClass> myList = new List<MyClass>(Enumerable.Repeat(new MyClass(), 100));

当然这不是最好的解决方案...

注意:如果您想要按键排序的集合,您也可以使用SortedList 而不是Dictionary

SortedList&lt;TKey, TValue&gt; :表示键/值对的集合,这些键/值对基于关联的 IComparer 实现按键排序。

【讨论】:

    【解决方案2】:

    如果您需要无法使用列表的键/值对,则需要字典。 实现非常快,所以不要太担心性能(只要你不把太多的值放在里面)。

    你可以遍历它

    foreach(KeyValuePair<int, string> kvp in dict)
    {
    }
    

    如果您需要订购,可以使用列表:

    List<int> ordered = new List(dict.Keys);
    ordered.Sort();
    
    foreach(int key in ordered)
    {
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-10
      • 1970-01-01
      • 1970-01-01
      • 2016-06-10
      • 2011-03-10
      • 2013-01-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多