在C#中插入内部列表

时间:2013-12-30 12:32:25

标签: c#

我正在初始化我的列表,如下所示 -

 List<string> lFiles = new List<string>(12);

现在我想在特定索引处添加/插入我的字符串。

像我在下面使用的那样 -

 lFiles.Insert(6,"File.log.6");

它抛出除了 - “索引必须在列表的范围内。”

初始化时我已经声明了List的容量,但我仍然无法在随机索引中插入字符串。

有人知道我错过了什么吗?

5 个答案:

答案 0 :(得分:3)

将int32作为参数的构造函数不会将项添加到列表中,它只是预先分配一些容量以获得更好的性能(这是实现细节)。在您的情况下,您的列表仍然是空的。

答案 1 :(得分:1)

您正在初始化列表的容量(基本上为了性能目的设置内部数组的初始大小),但它实际上并没有向列表中添加任何元素。

检查此问题的最简单方法是尝试:

var list1 = new List<int>();
var list2 = new List<int>(12);
Console.WriteLine(list1.Count);  //output is 0
Console.WriteLine(list2.Count);  //output is 0

这表明您仍然列表中没有任何元素。

为了初始化使用默认或空白元素填充数组,您需要实际将某些内容放入列表中。

int count = 12;
int value = 0
List<T> list = new List<T>(count);
list.AddRange(Enumerable.Repeat(value, count));

答案 2 :(得分:1)

与列表有一点混淆。当您为构造函数提供一些容量时,它会创建提供大小的内部数组,并使用默认值T填充它:

public List(int capacity)
{
    if (capacity < 0)
       throw new ArgumentException();

    if (capacity == 0)        
        this._items = List<T>._emptyArray;        
    else        
        this._items = new T[capacity];        
}

但是list不会将这些默认值视为添加到列表中的项目。是的,这有点令人困惑。内存是为数组分配的,但列表中的项目数仍然为零。你可以检查一下:

List<string> lFiles = new List<string>(12);
Console.WriteLine(lFiles.Count); // 0
Console.WriteLine(lFiles.Capacity); // 12

Count不返回内部数据结构的大小,它返回列表的“逻辑”大小(即添加但未删除的项目数):

public int Count
{  
    get { return this._size; }
}

只有在添加或删除要列出的项目时才会更改大小。 E.g。

public void Add(T item)
{
    if (this._size == this._items.Length)    
        this.EnsureCapacity(this._size + 1); // resize items array

    this._items[this._size++] = item; // change size
    this._version++;
}

当您在特定索引处插入某个项目时,list不会检查是否为items数组分配了足够的空间(检查是否正确,但仅在当前容量不足时调整内部数组的大小)。列表验证列表中是否有足够的项目包含(即已添加但未删除):

public void Insert(int index, T item)
{
    if (index > this._size) // here you get an exception, because size is zero
       throw new ArgumentOutOfRangeException();

    if (this._size == this._items.Length)    
        this.EnsureCapacity(this._size + 1); // resize items

    if (index < this._size)    
        Array.Copy(_items, index, this._items, index + 1, this._size - index);

    this._items[index] = item;
    this._size++;
    this._version++;
}

答案 3 :(得分:0)

容量只是暗示期望有多少元素。您的列表中仍然没有元素。

答案 4 :(得分:0)

我想您可能想要使用new Dictionary<int, string>(),而不是列表。

这将允许您使用int作为键来设置和查找值:

否则,如果你想使用基于位置的“列表”,你应该只使用一个字符串数组(但请注意,这不会让你自动调整大小):

var arr = new string[12];
arr[6] = "string at position 6";