【问题标题】:Insert int into an empty List<int> at a specific index在特定索引处将 int 插入空 List<int>
【发布时间】:2020-05-28 16:31:25
【问题描述】:

我意识到如果我的列表是空的,我不能在第三个索引处插入一些东西,因为它会抛出一个越界错误。

List<int> list = new List<int>();
list.Insert(3, 1000); //System.ArgumentOutOfRangeException

我必须用 null 填充第一个和第二个元素,以便我能够在第三个索引处插入一些东西。这似乎是不必要的。但是如果它是一个数组,我可以在任何我想要的索引中插入一些东西,即使之前的索引没有被分配。

int[] arr = new int[100];
arr[3] = 1000; //no error

有什么方法可以在不填充前一个索引的情况下插入特定索引处的空列表?或者还有其他更好的收藏吗?

【问题讨论】:

  • int 数组的元素始终被定义 - 它们自动为 0
  • List&lt;int&gt; list = new List&lt;int&gt;(); list.Insert(3, 1000); 的等价物是int[] arr = new int[0]; arr[3] = 1000;。奇怪的是,它引发了一个不同的错误。
  • 换句话说,调用new List&lt;int&gt;() 定义了一个空列表,但调用new int[100] 会创建一个包含100 元素的数组——所以调用new int[0] 会创建一个空数组。
  • @MichaelRandall - 这不是重复的。它可能会帮助 OP 前进,但它不能回答他的具体问题。
  • @Enigmativity 这就是为什么没有 dup 锤子的原因,虽然你是对的

标签: c# arrays list collections


【解决方案1】:

其他集合类型

或者还有其他更好的收藏吗?

您可以使用Dictionary。使用示例:

using System.Collections.Generic;

...

var items = new Dictionary<int, int>();
items.Add(3, 1000); // will throw error if 3 already exists

// Or update 
items[3] = 1000: // will not throw error if already exists or doesn't exist!

请注意,不保证字典的顺序。来自docs

项目返回的顺序是不确定的。

如果您需要订购保证,您可以使用SortedListSortedDictionary.

using System.Collections.Generic;

...

var items = new SortedList<int, int>();
items.Add(3, 1000); // will throw error if 3 already exists

// Or update 
items[3] = 1000: // will not throw error if already exists or doesn't exist!
using System.Collections.Generic;

...

var items = new SortedDictionary<int, int>();
items.Add(3, 1000); // will throw error if 3 already exists

// Or update 
items[3] = 1000: // will not throw error if already exists or doesn't exist!

SortedList 和 SortedDictionary 的区别在于性能。引用自docs

这两个类的不同之处在于内存使用和插入和删除速度

与列表和数组相比,(Sorted)Dictionary 和 SortedList 的工作方式有点不同。我建议在使用其中之一时阅读链接的 Microsoft 文档。

null 列表或数组中的值

我必须用 null 填充第一个和第二个元素,以便能够在第三个索引处插入一些东西

请注意,您不能在整数列表或数组中添加 null 值。这只有在“可为空的整数”中才有可能。 (所以new List&lt;int?&gt;()

【讨论】:

  • 正确答案。字典更适合这种情况。
  • 谢谢!但回想起来,我认为 SortedList 更好,因为有保证的排序。更新了我的答案。
  • 或 SortedDictionary ;) 也添加到了答案中。
【解决方案2】:

插入列表是在指定位置向列表添加另一个元素。这与在数组中的索引处设置值不同。如果您有一个包含 100 个项目的数组并将值设置为索引 3,那么数组中仍然有 100 个项目。如果您有一个包含 100 个项目的列表,并且您在索引 3 处插入了一些内容,那么您现在有一个包含 101 个项目的列表。

【讨论】:

  • 这如何回答 OP 提出的具体问题?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-02
  • 1970-01-01
  • 2011-05-17
  • 1970-01-01
相关资源
最近更新 更多