C#の辞書クラス
C#の辞書は、キーと値のコレクションです。これは、System.Collection.Generics名前空間のジェネリックコレクションクラスです。
構文
以下は構文です-
public class Dictionary<TKey,TValue>
上記では、キーパラメータはディクショナリ内のキーのタイプですが、TValueは値のタイプです。
例
辞書を作成して、いくつかの要素を追加しましょう-
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(){
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("One", "John");
dict.Add("Two", "Tom");
dict.Add("Three", "Jacob");
dict.Add("Four", "Kevin");
dict.Add("Five", "Nathan");
Console.WriteLine("Key/value pairs...");
foreach(KeyValuePair<string, string> res in dict){
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
}
} 出力
これにより、次の出力が生成されます-
Key/value pairs... Key = One, Value = John Key = Two, Value = Tom Key = Three, Value = Jacob Key = Four, Value = Kevin Key = Five, Value = Nathan
例
それでは、例を見て、いくつかのキーを削除しましょう-
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(){
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("One", "Kagido");
dict.Add("Two", "Ngidi");
dict.Add("Three", "Devillers");
dict.Add("Four", "Smith");
dict.Add("Five", "Warner");
Console.WriteLine("Count of elements = "+dict.Count);
Console.WriteLine("Removing some keys...");
dict.Remove("Four");
dict.Remove("Five");
Console.WriteLine("Count of elements (updated) = "+dict.Count);
Console.WriteLine("\nKey/value pairs...");
foreach(KeyValuePair<string, string> res in dict){
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
Console.Write("\nAll the keys..\n");
Dictionary<string, string>.KeyCollection allKeys = dict.Keys;
foreach(string str in allKeys){
Console.WriteLine("Key = {0}", str);
}
}
} 出力
これにより、次の出力が生成されます-
Count of elements = 5 Removing some keys... Count of elements (updated) = 3 Key/value pairs... Key = One, Value = Kagido Key = Two, Value = Ngidi Key = Three, Value = Devillers All the keys.. Key = One Key = Two Key = Three
-
C#でクラスを変換する
Convertクラスには、基本データ型を別の基本データ型に変換するメソッドがあります。いくつかの例を見てみましょう- Convert.ToBoolean()メソッド C#では、指定された値を同等のブール値に変換するために使用されます。 構文 以下は構文です- public static bool ToBoolean (string val, IFormatProvider provider); 上記では、ValはTrueStringまたはFalseStringのいずれかの値を含む文字列ですが、プロバイダーはカルチャ固有のフォーマット情報を提供するオブジェクトです。 例 Convert
-
C#のコンソールクラス
C#のConsoleクラスは、コンソールアプリケーションの標準の入力、出力、およびエラーストリームを表すために使用されます。 C#のコンソールクラスプロパティの例をいくつか見てみましょう- Console.CursorLeftプロパティ C#でコンソールのCursorLeftを変更するには、Console.CursorLeftプロパティを使用します。 例 例を見てみましょう- using System; class Demo { public static void Main (string[] args) { Cons