List<int> MyLottoNumbers = new List<int>();
MyLottoNumbers[0] = int.Parse(textBoxNum1.Text);
textBoxNum1有5添加文本框的值列出
此代碼提供了錯誤
Index was out of range. Must be non-negative and less than the size of the collection.
爲什麼值?
List<int> MyLottoNumbers = new List<int>();
MyLottoNumbers[0] = int.Parse(textBoxNum1.Text);
textBoxNum1有5添加文本框的值列出
此代碼提供了錯誤
Index was out of range. Must be non-negative and less than the size of the collection.
爲什麼值?
試試這個,而不是使用正則表達式和linq來創建和解析列表。
注意它假定用戶在空間是把拆就如「5 12 15」這樣:
if (string.IsNullOrWhiteSpace(textBoxNum1.Text) == false)
{
MyLottoNumbers = Regex.Matches(textBoxNum1.Text, @"([^\s]+)\s*")
.OfType<Match>()
.Select(mt => int.Parse(mt.Groups[0].Value))
.ToList();
}
else
{
MyLottoNumbers = new List<int>(); // Create empty list as to not throw an exception.
}
+1。爲了這個問題的最佳答案呢。幹得好! – Brian
這是因爲你的列表目前是空的,所以你不能設置第一個索引(因爲它不存在)。如果你這樣做:
List<int> MyLottoNumbers = new List<int>();
MyLottoNumbers.Add(int.Parse("5"));
MyLottoNumbers[0] = int.Parse("7");
它的工作原理,因爲該索引已設置。
如果你想在前面插入,走這條路:
List<int> MyLottoNumbers = new List<int>();
MyLottoNumbers.Insert(0, int.Parse(textBoxNum1.Text));
創建一個新的列表與
new List<int>();
創建一個具有0大小(http://msdn.microsoft.com/en-us/library/4kf43ys3(v=vs.110).aspx)的列表。
隨着[0]你正在嘗試在該位置0獲得元素與零大小的列表不能有一個0索引 - >索引超出範圍
見http://www.dotnetperls.com/list關於如何使用示例名單。
在這種情況下,這將是:
MyLottoNumbers.Add(int.Parse(textBoxNum1.Text));
添加並在列表的末尾添加值。
是的但如果我必須添加一個值到一個特定的列表值爲 說明?
看起來你想添加一個特定的索引值。如果您在設計時知道列表的大小,則應考慮使用數組而不是列表。
您需要.Add()
您的文本框的值爲您的List
。就像這樣:
List<int> MyLottoNumbers = new List<int>();
MyLottoNumbers.Add(int.Parse(textBoxNum1.Text);
當你new
了List
,它的大小設置爲0,直到你.Add()
項目給它。
如果你讀的異常消息,它說:
指數超出範圍。必須是非負數並且小於集合的大小
發生這種情況是因爲創建時List有0個元素長度(檢查MyLottoNumbers.Count)。
公開名單()System.Collections.Generic.List
的 會員摘要:這是在構造函數中的摘要指出初始化 System.Collections.Generic.List類的新實例空並具有 默認初始容量。
您正在嘗試使用索引:
公共牛逼這個[INT指數] {設置;得到; } System.Collections.Generic.List的成員
摘要:獲取或設置指定索引處的元素。
將元素設置在位置0.但是,您會得到一個異常,因爲實際上在位置0處沒有元素(因爲列表爲空)。
列表大小增加時執行MyLottoNumbers.Add
。
你真正需要做的是:
MyLottoNumbers.Add(int.Parse(textBoxNum1.Text);
NB: 的列表和數組之間的區別這一個:創建時列表是空的,而數組不是。所以,你可以使用一個數組重寫你的榜樣:
int[] MyLottoNumbers = new int[25];
MyLottoNumbers[0] = int.Parse("5");
嘗試MyLottoNumbers.Add(int.Parse(textBoxNum1.Text); – Florian
肯定的,但如果我有如圖所示的價值添加到特定列表值 – user1438082
?如果你想在指定的值插入值,試試這個:MyLottoNumbers.Insert(指數值) – PushCode