C#
 Computer >> コンピューター >  >> プログラミング >> C#

コレクション要素をC#の配列にコピーする


コレクション要素を配列にコピーするためのコードは次のとおりです-

using System;
using System.Collections.ObjectModel;
public class Demo {
   public static void Main(){
      Collection<string> col = new Collection<string>();
      col.Add("One");
      col.Add("Two");
      col.Add("Three");
      col.Add("Four");
      col.Add("Five");
      col.Add("Six");
      col.Add("Seven");
      col.Add("Eight");
      Console.WriteLine("Collection....");
      foreach(string str in col){
         Console.WriteLine(str);
      }
      string[] strArr = new string[10];
      col.CopyTo(strArr, 2);
      Console.WriteLine("\nArray...");
      foreach(string str in strArr){
         Console.WriteLine(str);
      }
   }
}

出力

これにより、次の出力が生成されます-

Collection....
One
Two
Three
Four
Five
Six
Seven
Eight

Array...

One
Two
Three
Four
Five
Six
Seven
Eight

別の例を見てみましょう-

using System;
using System.Collections.ObjectModel;
public class Demo {
   public static void Main(){
      Collection<string> col = new Collection<string>();
      col.Add("One");
      col.Add("Two");
      col.Add("Three");
      col.Add("Four");
      col.Add("Five");
      Console.WriteLine("Collection....");
      foreach(string str in col){
         Console.WriteLine(str);
      }
      string[] strArr = new string[10];
      col.CopyTo(strArr, 3);
      Console.WriteLine("\nArray...");
      foreach(string str in strArr){
         Console.WriteLine(str);
      }
   }
}

出力

これにより、次の出力が生成されます-

Collection....
One
Two
Three
Four
Five

Array...

One
Two
Three
Four
Five

  1. C#のコレクションから要素を取得する

    リストコレクションの例を見てみましょう。 要素を設定しました- List<int> list = new List<int>(); list.Add(20); list.Add(40); list.Add(60); list.Add(80); ここで、リストから最初の要素を取得する必要があるとします。そのためには、このようにインデックスを設定します- int a = list[0]; 以下は、リストコレクションから要素を取得する方法を示す例です- 例 using System; using System.Collections.Generic; class De

  2. コレクションの要素をシャッフルするJavaプログラム

    この記事では、コレクションの要素をシャッフルする方法を理解します。コレクションは、オブジェクトのグループを格納および操作するためのアーキテクチャを提供するフレームワークです。 JavaCollectionsは、検索、並べ替え、挿入、操作、削除など、データに対して実行するすべての操作を実行できます。 以下は同じのデモンストレーションです- 入力がであると仮定します − Input list: [Java, program, is, fun, and, easy] 必要な出力は − The shuffled list is: [is, easy, program, and, fun, J