Home  >  Article  >  Backend Development  >  In C#, how to copy items from one list to another without using foreach?

In C#, how to copy items from one list to another without using foreach?

王林
王林forward
2023-09-02 20:41:141182browse

在 C# 中,如何在不使用 foreach 的情况下将项目从一个列表复制到另一个列表?

List is a collection of strongly typed objects that can be accessed through an index And has methods for sorting, searching, and modifying lists. It is the generic version of ArrayList under System.Collection.Generic Namespaces.

List is equivalent to ArrayList, which implements IList.

It is located under the System.Collection.Generic namespace.

List can contain elements of the specified type. It provides compile-time types Check and do not perform boxing-unboxing as it is generic.

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 performs faster and less error-prone than ArrayList.

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 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

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete