C#のディクショナリを反復処理する列挙子を取得します
ディクショナリを反復処理する列挙子を取得するには、コードは次のとおりです-
例
using System;
using System.Collections;
using System.Collections.Generic;
public class Demo {
public static void Main(){
Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(100, "Laptop");
dict.Add(150, "Desktop");
dict.Add(200, "Earphone");
dict.Add(300, "Tablet");
dict.Add(500, "Speakers");
dict.Add(750, "HardDisk");
dict.Add(1000, "SSD");
IDictionaryEnumerator demoEnum = dict.GetEnumerator();
Console.WriteLine("Enumerator iterating key-value pairs...");
while (demoEnum.MoveNext())
Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
}
} 出力
これにより、次の出力が生成されます-
Enumerator iterating key-value pairs... Key = 100, Value = Laptop Key = 150, Value = Desktop Key = 200, Value = Earphone Key = 300, Value = Tablet Key = 500, Value = Speakers Key = 750, Value = HardDisk Key = 1000, Value = SSD
例
別の例を見てみましょう-
using System;
using System.Collections;
using System.Collections.Generic;
public class Demo {
public static void Main(){
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("One", "Laptop");
dict.Add("Two", "Desktop");
dict.Add("Three", "Earphone");
dict.Add("Four", "Tablet");
dict.Add("Five", "Speakers");
dict.Add("Six", "HardDisk");
dict.Add("Seven", "SSD");
dict.Add("Eight", "Keyboard");
dict.Add("Nine", "Mouse");
IDictionaryEnumerator demoEnum = dict.GetEnumerator();
Console.WriteLine("Enumerator iterating key-value pairs...");
while (demoEnum.MoveNext())
Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
}
} 出力
これにより、次の出力が生成されます-
Enumerator iterating key-value pairs... Key = One, Value = Laptop Key = Two, Value = Desktop Key = Three, Value = Earphone Key = Four, Value = Tablet Key = Five, Value = Speakers Key = Six, Value = HardDisk Key = Seven, Value = SSD Key = Eight, Value = Keyboard Key = Nine, Value = Mouse
-
C#で大文字と小文字を区別しない辞書
大文字と小文字を区別せずに比較するには、大文字と小文字を区別しない辞書を使用します。 辞書を宣言するときに、大文字と小文字を区別しない辞書を取得するには、次のプロパティを設定します- StringComparer.OrdinalIgnoreCase このようなプロパティを追加します- Dictionary <string, int> dict = new Dictionary <string, int> (StringComparer.OrdinalIgnoreCase); これが完全なコードです- 例 using System; using System.Col
-
辞書からキーのリストを取得するC#プログラム
辞書要素を設定する- Dictionary<int, string> d = new Dictionary<int, string>(); // dictionary elements d.Add(1, "One"); d.Add(2, "Two"); d.Add(3, "Three"); d.Add(4, "Four"); d.Add(5, "Five"); d.Add(6, "Six"); d.Add(7, "Seven");