ken*_*awg 1 c# arrays collections list
我意识到如果我的列表是空的,我不能在第三个索引处插入一些东西,因为它会抛出越界错误。
List<int> list = new List<int>();
list.Insert(3, 1000); //System.ArgumentOutOfRangeException
Run Code Online (Sandbox Code Playgroud)
我将不得不用 null 填充第一个和第二个元素,以便我能够在第三个索引处插入一些东西。这似乎没有必要。但是如果它是一个数组,即使没有分配以前的索引,我也可以向我想要的任何索引插入一些东西。
int[] arr = new int[100];
arr[3] = 1000; //no error
Run Code Online (Sandbox Code Playgroud)
有什么方法可以在不填充前一个索引的情况下插入特定索引处的空列表?或者有其他更好的收藏吗?
或者有其他更好的收藏吗?
您可以使用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!
Run Code Online (Sandbox Code Playgroud)
请注意,不保证字典的顺序。从文档
项目返回的顺序未定义。
如果您需要保证排序,您可以使用SortedList或 SortedDictionary。
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!
Run Code Online (Sandbox Code Playgroud)
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!
Run Code Online (Sandbox Code Playgroud)
SortedList 和 SortedDictionary 之间的区别在于性能。来自文档的引用:
这两个类的不同之处在于内存使用以及插入和删除的速度
(Sorted)Dictionary 和 SortedList 与列表和数组相比有点不同。我建议在使用其中之一时阅读链接的 Microsoft 文档。
null 列表或数组中的值我将不得不用 null 填充第一个和第二个元素,以便我能够在第三个索引处插入一些东西
请注意,您不能null在整数列表或数组中添加值。只有“可空整数”才有可能做到这一点。(所以new List<int?>())