Home >Backend Development >C#.Net Tutorial >In C#, how to copy items from one list to another without using foreach?
List
List
It is located under the System.Collection.Generic namespace.
List
You can add elements using the Add(), AddRange() method or collection initializer grammar.
Elements can be accessed by passing the index, for example my list[0]. Indexing starts from zero.
List
Lists can be accessed through indexes, for/foreach loops, and using LINQ queries. The index of the list starts from zero.
Pass the index in square brackets to access individual list items, the same as for arrays. use
A foreach or for loop for iterating over a List
class Program{ public static void Main(){ List<int>originalList=new List<int>(){1,2,3,4,5,7,8,9}; List<Int32>copy = new List<Int32>(originalList); foreach (var item in copy){ System.Console.WriteLine(item); } Console.ReadLine(); } }
1 2 3 4 5 7 8 9
class Program{ public static void Main(){ List<int>originalList = new List<int>() { 1, 2, 3, 4, 5, 7, 8, 9 }; List<Int32> copy = originalList.ToList(); foreach (var item in copy){ System.Console.WriteLine(item); } Console.ReadLine(); } }
1 2 3 4 5 7 8 9
class Program{ public static void Main(){ List<int> originalList = new List<int>() { 1, 2, 3, 4, 5, 7, 8, 9 }; List<Int32> copy = originalList.GetRange(0, 3); foreach (var item in copy){ System.Console.WriteLine(item); } Console.ReadLine(); } }
1 2 3
The above is the detailed content of In C#, how to copy items from one list to another without using foreach?. For more information, please follow other related articles on the PHP Chinese website!