How do I copy items from list to list without foreach in C#?

CsharpServer Side ProgrammingProgramming

The List<T> is a collection of strongly typed objects that can be accessed by index and having methods for sorting, searching, and modifying list. It is the generic version of the ArrayList that comes under System.Collection.Generic namespace.

List<T> equivalent of the ArrayList, which implements IList<T>.

It comes under System.Collection.Generic namespace.

List<T>can contain elements of the specified type. It provides compile-time type checking and doesn't perform boxing-unboxing because it is generic.

Elements can be added using the Add(), AddRange() methods or collection-initializer syntax.

Elements can be accessed by passing an index e.g. myList[0]. Indexes start from zero. List<T> performs faster and less error-prone than the ArrayList.

A list can be accessed by an index, a for/foreach loop, and using LINQ queries. Indexes of a list start from zero.

Pass an index in the square brackets to access individual list items, same as array. Use a foreach or for loop to iterate a List<T> collection.

Method 1

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();
   }
}

Output

1
2
3
4
5
7
8
9

Method 2

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();
   }
}

Output

1
2
3
4
5
7
8
9

Method 3

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();
   }
}

Output

1
2
3
raja
Published on 25-Sep-2020 14:30:53
Advertisements