c#で、dictionaryをlistに変更する方法は何ですか。
C#のDictionaryをListに変換するには、DictionaryのKeysプロパティとValuesプロパティを使用します。Keysプロパティを使ってDictionaryのすべてのキーを取得し、Valuesプロパティを使ってすべての値を取得します。その後、Listのコンストラクタを使用してキーと値をListに変換します。以下は例です:
Dictionary<string, int> myDictionary = new Dictionary<string, int>();
myDictionary.Add("Apple", 1);
myDictionary.Add("Banana", 2);
myDictionary.Add("Orange", 3);
List<string> keys = new List<string>(myDictionary.Keys);
List<int> values = new List<int>(myDictionary.Values);
Console.WriteLine("Keys:");
foreach (string key in keys)
{
Console.WriteLine(key);
}
Console.WriteLine("Values:");
foreach (int value in values)
{
Console.WriteLine(value);
}
結果:
Keys:
Apple
Banana
Orange
Values:
1
2
3
上記の例では、まずDictionaryオブジェクトを定義し、いくつかのキーと値を追加します。次に、Keys属性を使用してキーをリストに、Values属性を使用して値をリストに変換します。最後に、foreachループを使用してリストの要素を出力します。