![](/img/trans.png)
[英]Error: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection
[英]System.ArgumentOutOfRangeException: 'Index was out of range. copy from one list to another
我構建了以下程序,但出現超出范圍錯誤。 基本上我想將值從一個列表復制到另一個列表(從a
到b
):
List<int> a = new List<int> { 99, 2, 3, 4, 5, 6 };
List<int> b = new List<int>(6);
for ( int i = 0; i < a.ToArray().Length; i++ )
{
a[i].ToString().Insert(0, b[i].ToString());
}
for ( int i = 0; i < a.ToArray().Length; i++ )
{
Console.WriteLine(b[i]);
}
Console.ReadKey();
只需通過在第一個列表上調用ToList()
將值從第一個列表復制到第二個列表:
List<int> uzytkownik = new List<int>() { 99, 2, 3, 4, 5, 6 };
List<int> uzytkownik1 = uzytkownik.ToList();//only values are copied, not the reference to the first list
for (int i = 0; i < uzytkownik1.Count; i++)
{
Console.WriteLine(uzytkownik1[i]);
}
Console.ReadKey();
如果必須使用 for 循環,則:
List<int> uzytkownik = new List<int>() { 99, 2, 3, 4, 5, 6 };
List<int> uzytkownik1 = new List<int>();
for (int i = 0; i < uzytkownik.Count; i++)
{
uzytkownik1.Add(uzytkownik[i]);
}
for (int i = 0; i < uzytkownik1.Count; i++)
{
Console.WriteLine(uzytkownik1[i]);
}
Console.ReadKey();
List<T>
已經有這種工作的方法。 List<T>.AddRange(IEnumerable<T>)
List<int> a = new List<int> { 99, 2, 3, 4, 5, 6 };
List<int> b = new List<int>(6);
b.AddRange( a );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.