简体   繁体   English

在C#中插入内部列表

[英]Insert inside list in C#

I am initializing my list as below - 我正在初始化我的清单如下 -

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

and now I want to add/insert my string at specific index. 现在我想在特定索引处添加/插入我的字符串。

like I am using below - 就像我在下面使用 -

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

it it throwing excepton as - "Index must be within the bounds of the List." 它抛出除了 - “索引必须在列表的范围内。”

While initializing I have declared capacity of List but still I am not able insert strings at random indexes. 在初始化时我已经声明了List的容量,但我仍然无法在随机索引处插入字符串。

Anybody knows what I am missing?? 谁知道我错过了什么?

The constructor that takes an int32 as parameter doesn't add items to the list, it just pre-allocates some capacity for better performances (this is implementation details). 将int32作为参数的构造函数不会将项添加到列表中,它只是预先分配一些容量以获得更好的性能(这是实现细节)。 In your case, your list is still empty. 在您的情况下,您的列表仍然是空的。

You are initializing the capacity of the list (basically setting the initial size of the internal array for performance purposes), but it does not actually add any elements to the list. 您正在初始化列表的容量(基本上为了性能目的设置内部数组的初始大小),但它实际上并没有向列表中添加任何元素。

The easiest way to check this is try this: 检查这个的最简单方法是试试这个:

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

This shows that you still don't have any elements in your list. 这表明您的列表中仍然没有任何元素。

In order to initialize populate the array with default or blank elements, you need to actually put something into the list. 为了初始化使用默认或空白元素填充数组,您需要实际将一些内容放入列表中。

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

There is small confusion with list. 与列表有一点混淆。 When you provide some capacity for constructor, it creates internal array of provided size and fills it with default values of T : 当您为构造函数提供一些容量时,它会创建提供大小的内部数组,并使用默认值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];        
}

But list does not treat that default values as items added to list. 但是列表不会将这些默认值视为添加到列表中的项目。 Yep, that is confusing a little. 是的,这有点令人困惑。 Memory is allocated for array, but count of items in list still will be zero. 内存是为数组分配的,但列表中的项目数仍然为零。 You can check it: 你可以检查一下:

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

Count does not returns size of internal data structure, it returns 'logical' size of list (ie number of items which was added and not removed): Count不返回内部数据结构的大小,它返回列表的“逻辑”大小(即添加但未删除的项目数):

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

And size is changed only when you add or remove items to list. 仅当您添加或删除要列出的项目时,才会更改大小。 Eg 例如

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++;
}

When you are inserting some item at specific index, list does not checks if enough space allocated for items array (well it checks, but just for resizing inner array if current capacity is not enough). 当您在特定索引处插入某个项目时,list不会检查是否为items数组分配了足够的空间(检查是否正确,但仅在当前容量不足时调整内部数组的大小)。 List verifies that there is enough items already contained in list (ie added, but not removed): List验证列表中是否已包含足够的项目(即已添加但未删除):

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++;
}

The capacity is just a hint how many elements to expect. 容量只是暗示了预期会有多少元素。 There are still no elements in your list. 您的列表中仍然没有元素。

I think you might want to use a new Dictionary<int, string>() , not a list. 我想您可能想要使用new Dictionary<int, string>() ,而不是列表。

That will let you use the int as a key to set and look up values by: 这将允许您使用int作为键来设置和查找值:

Otherwise, if you want to use position-based "list", you should just use an string-array instead (but note that that will not let you adjust the size automatically): 否则,如果你想使用基于位置的“列表”,你应该只使用一个字符串数组(但请注意,这不会让你自动调整大小):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM