在 C# 中,我有一个用例,其中我有一个来自 int
的映射s 到集合。
int
s 是一个从 1 到 n 的密集(但不是压缩)集合,其中 n 是未知的。- 单元格将以随机顺序加载。
- 每个电池的边际成本应该是理想的(与
List<T>
或T[]
一样好) - 我希望按需默认填充单元格
最好的结构是什么?
A List<T>
会很好地工作(在空间上比 Dictionary<>
更好)并且通过从中派生我可以获得我想要的很多东西,但是有更好的东西吗?正如最好的代码是您不编写的代码。
最佳答案
A Dictionary<int, Cell>
听起来很适合我。或者你可以使用 List<Cell>
很容易,只需确保在必要时扩展它:
public static void EnsureCount<T>(List<T> list, int count)
{
if (list.Count > count)
{
return;
}
if (list.Capacity < count)
{
// Always at least double the capacity, to reduce
// the number of expansions required
list.Capacity = Math.Max(list.Capacity*2, count);
}
list.AddRange(Enumerable.Repeat(default(T), list.Capacity-list.Count));
}
关于c# - 随机顺序填充的最佳 C# 数据结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/481334/