ハッシュテーブル要素をC#の配列インスタンスにコピーする
ハッシュテーブル要素を配列インスタンスにコピーするためのコードは次のとおりです-
例
using System;
using System.Collections;
public class Demo {
public static void Main(){
Hashtable hash = new Hashtable();
hash.Add("1", "AB");
hash.Add("2", "CD");
hash.Add("3", "EF");
hash.Add("4", "GH");
hash.Add("5", "IJ");
Console.WriteLine("Hashtable Key and Value pairs...");
foreach(DictionaryEntry entry in hash){
Console.WriteLine("{0} and {1} ", entry.Key, entry.Value);
}
Console.WriteLine("Copied to Array Instance...");
DictionaryEntry[] dictArr = new DictionaryEntry[hash.Count];
hash.CopyTo(dictArr, 0);
for (int i = 0; i < dictArr.Length; i++)
Console.WriteLine("Key = "+dictArr[i].Key + ", Value = " + dictArr[i].Value);
}
} 出力
これにより、次の出力が生成されます-
Hashtable Key and Value pairs... 1 and AB 2 and CD 3 and EF 4 and GH 5 and IJ Copied to Array Instance... Key = 1, Value = AB Key = 2, Value = CD Key = 3, Value = EF Key = 4, Value = GH Key = 5, Value = IJ
例
別の例を見てみましょう-
using System;
using System.Collections;
public class Demo {
public static void Main(){
Hashtable hash = new Hashtable(5);
hash.Add("1", "AB");
hash.Add("2", "CD");
Console.WriteLine("Hashtable Key and Value pairs...");
foreach(DictionaryEntry entry in hash){
Console.WriteLine("{0} and {1} ", entry.Key, entry.Value);
}
Console.WriteLine("Copied to Array Instance...");
DictionaryEntry[] dictArr = new DictionaryEntry[5];
hash.CopyTo(dictArr, 2);
for (int i = 0; i < dictArr.Length; i++)
Console.WriteLine("Key = "+dictArr[i].Key + ", Value = " + dictArr[i].Value);
}
} 出力
これにより、次の出力が生成されます-
Hashtable Key and Value pairs... 1 and AB 2 and CD Copied to Array Instance... Key = , Value = Key = , Value = Key = 1, Value = AB Key = 2, Value = CD Key = , Value =
-
C#のジャグ配列の要素のタイプは何ですか?
ジャグ配列は配列の配列であるため、その要素は参照型であり、nullに初期化されます。 ジャグ配列の操作方法を見てみましょう- ジャグ配列を宣言する- int [][] marks; ここで、それを初期化します。ここで、marksは5つの整数の配列です- int[][] marks = new int[][]{new int[]{ 40,57 },new int[]{ 34,55 }, new int[]{ 23,44 },new int[]{ 56, 78 }, new int[]{ 66, 79 } }; ここで、C#でのジャグ配列の完全な例を見て、それを実装する方法を学びましょう-
-
C#で整数配列の要素の平均を見つける方法は?
以下は整数配列です- int[] myArr = new int[6] { 8, 4, 2, 5, 9, 14 }; まず、配列の長さを取得し、配列をループして要素の合計を見つけます。その後、長さで割ります。 int len = myArr.Length; int sum = 0; int average = 0; for (int i = 0; i < len; i++) { sum += myArr[i