c# - 随机顺序填充的最佳 C# 数据结构?

标签 c# data-structures collections

在 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/

相关文章:

java - 我应该使用哪个 Java 集合?

c# - StreamReader ReadLine 抛出异常而不是返回 null

c# - Mono,asp.net C#和MVC的操作方法和教程

perl - 在 Perl 中插入散列的末尾

algorithm - 从前序和后序遍历中绘制树而不对树的形状做任何假设

java - Java 集的并集或交集

c# - 使用二进制格式写入和读取对象,u-sql

c# - 在响应 header 中传递非 ASCII 字符

r - 根据不同数据帧中第二个(较短)列的值将值分配给列

validation - Symfony2+Doctrine - 验证实体的一对多集合