[英]System.ArgumentOutOfRangeException: 'Index was out of range. copy from one list to another
I built following programm, but I get the out of range error.我构建了以下程序,但出现超出范围错误。 Basically I would like to copy values from one list to another (from a
to b
):基本上我想将值从一个列表复制到另一个列表(从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();
Just copy the values from the first list to the second list by calling ToList()
on the first list:只需通过在第一个列表上调用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();
If you have to use a for loop then:如果必须使用 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();
Have a look at the Array.CopyTo method.看看 Array.CopyTo 方法。
https://docs.microsoft.com/en-us/dotnet/api/system.array.copyto?view=netframework-4.8 https://docs.microsoft.com/en-us/dotnet/api/system.array.copyto?view=netframework-4.8
The List<T>
already has a method for that kind of work. 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.