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
):
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:
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:
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.
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>.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 );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.