Insert an internal list in C #

I initialize my list as shown below:

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

and now I want to add / paste my row to a specific index.

as i use below -

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

he throws, except as - "The index must be within the list."

During initialization, I declared the list capacity, but still I cannot insert rows into random indexes.

Does anyone know what I'm missing?

+4
source share
5 answers

The constructor, which accepts the int32 parameter as an element, does not add elements to the list, it just pre-allocates some capacity for better characteristics (these are implementation details). In your case, your list is still empty.

+3
source

( ), .

- :

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));
+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<string> lFiles = new List<string>(12);
Console.WriteLine(lFiles.Count); // 0
Console.WriteLine(lFiles.Capacity); // 12

, "" (.. , ):

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

. .

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

- , , ( , , ). , , (.. , ):

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

- , . .

0
source

I think you can use new Dictionary<int, string>(), not a list.

This will allow you to use int as a key to set and search for values ​​using:

Otherwise, if you want to use a positional “list”, you should just use a string array (but note that this will not allow you to automatically adjust the size):

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

All Articles