[英]Insert inside list in C#
我正在初始化我的清單如下 -
List<string> lFiles = new List<string>(12);
現在我想在特定索引處添加/插入我的字符串。
就像我在下面使用 -
lFiles.Insert(6,"File.log.6");
它拋出除了 - “索引必須在列表的范圍內。”
在初始化時我已經聲明了List的容量,但我仍然無法在隨機索引處插入字符串。
誰知道我錯過了什么?
將int32作為參數的構造函數不會將項添加到列表中,它只是預先分配一些容量以獲得更好的性能(這是實現細節)。 在您的情況下,您的列表仍然是空的。
您正在初始化列表的容量(基本上為了性能目的設置內部數組的初始大小),但它實際上並沒有向列表中添加任何元素。
檢查這個的最簡單方法是試試這個:
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));
與列表有一點混淆。 當您為構造函數提供一些容量時,它會創建提供大小的內部數組,並使用默認值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
Count不返回內部數據結構的大小,它返回列表的“邏輯”大小(即添加但未刪除的項目數):
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++;
}
當您在特定索引處插入某個項目時,list不會檢查是否為items數組分配了足夠的空間(檢查是否正確,但僅在當前容量不足時調整內部數組的大小)。 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++;
}
容量只是暗示了預期會有多少元素。 您的列表中仍然沒有元素。
我想您可能想要使用new Dictionary<int, string>()
,而不是列表。
這將允許您使用int作為鍵來設置和查找值:
否則,如果你想使用基於位置的“列表”,你應該只使用一個字符串數組(但請注意,這不會讓你自動調整大小):
var arr = new string[12];
arr[6] = "string at position 6";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.