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

スタックをC#の配列にコピーします


スタックを配列にコピーするためのコードは次のとおりです-

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      Stack<int> stack = new Stack<int>();
      stack.Push(10);
      stack.Push(20);
      stack.Push(30);
      stack.Push(40);
      stack.Push(50);
      stack.Push(60);
      stack.Push(70);
      stack.Push(80);
      stack.Push(90);
      stack.Push(100);
      Console.WriteLine("Displaying the stack...");
      foreach(int val in stack){
         Console.WriteLine(val);
      }
      int[] intArr = new int[stack.Count];
      stack.CopyTo(intArr, 0);
      Console.WriteLine("Displaying the array...");
      foreach(int val in intArr){
         Console.WriteLine(val);
      }
   }
}

出力

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

Displaying the stack...
100
90
80
70
60
50
40
30
20
10
Displaying the array...
100
90
80
70
60
50
40
30
20
10

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

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      Stack<int> stack = new Stack<int>();
      stack.Push(10);
      stack.Push(20);
      stack.Push(30);
      stack.Push(40);
      stack.Push(50);
      Console.WriteLine("Displaying the stack...");
      foreach(int val in stack){
         Console.WriteLine(val);
      }
      int[] intArr = new int[10];
      stack.CopyTo(intArr, 2);
      Console.WriteLine("Displaying the array...");
      foreach(int val in intArr){
         Console.WriteLine(val);
      }
   }
}

出力

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

Displaying the stack...
50
40
30
20
10
Displaying the array...
0
0
50
40
30
20
10
0
0
0

  1. C#のStackクラスのCountプロパティとは何ですか?

    Stackクラスに追加された要素の数を見つけるには、Countプロパティを使用する必要があります。 まず、スタックに要素を追加しましょう- Stack st = new Stack(); st.Push('H'); st.Push('I'); st.Push('J'); st.Push('K'); st.Push('L'); st.Push('M'); st.Push('N'); st.Push('O'); 次に、スタック内の要素の数を数えます- Console

  2. C#での配列コピー

    配列を使用します。ある配列のセクションを別の配列にコピーするには、C#のcopyメソッドを使用します。 元の配列には10個の要素があります- int [] n = new int[10]; /* n is an array of 10 integers */ 配列1のセクションをコピーする新しい配列には、5つの要素があります- int [] m = new int[5]; /* m is an array of 5 integers */ array.copy()メソッドを使用すると、ソース配列と宛先配列を追加できます。それで、2番目の配列に含まれる最初の配列のセクションのサイズを含めます