どうも、ちょげ(@chogetarou)です。
Dictionary(連想配列)の要素をKeyValuePairのリストに変換する方法を紹介します。
方法

Dictionary(連想配列)の要素をKeyValuePairのリストに変換する方法は、3つあります。
List<T>()
1つ目は、List<T>()を使う方法です。
まず、「new List<T>()」を記述します。
そして、List<T>()の引数にDictionaryを指定します。
List<KeyValuePair<TKey, TValue>> items = new List<KeyValuePair<TKey, TValue>>(myDict);
上記のList<T>()は、引数に指定したDictionary(連想配列)をKeyValuePairのリストに変換します。
使用例
using System;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
Dictionary<string, int> numbers = new Dictionary<string, int>()
{
{ "one", 1 },
{ "two", 2 },
{ "three", 3 },
{ "four", 4 },
{ "five", 5 },
};
List<KeyValuePair<string, int>> items = new List<KeyValuePair<string, int>>(numbers);
Console.WriteLine(String.Join(",", items)); //[one, 1],[two, 2],[three, 3],[four, 4],[five, 5]
}
}
ToList()
2つ目は、ToList()を使う方法です。
まず、System.Linqを導入します。
using System.Linq;
そして、DictionaryからToList()を呼び出します。
List<KeyValuePair<TKey, TValue>> items = myDict.ToList();
上記のToList()は、呼び出したDictionary(連想配列)の要素をKeyValuePairのリストに変換します。
使用例
using System;
using System.Collections.Generic;
using System.Linq;
public class Example
{
public static void Main()
{
Dictionary<string, int> numbers = new Dictionary<string, int>()
{
{ "one", 1 },
{ "two", 2 },
{ "three", 3 },
{ "four", 4 },
{ "five", 5 },
};
List<KeyValuePair<string, int>> items = numbers.ToList();
Console.WriteLine(String.Join(",", items)); //[one, 1],[two, 2],[three, 3],[four, 4],[five, 5]
}
}
foreachループ
3つ目は、foreachループを使う方法です。
まず、リストを用意します。
List<KeyValuePair<TKey, TValue>> items = new List<KeyValuePair<TKey, TValue>>();
Dictionaryをforeachでループします。
foreachのループ処理で、リストからAdd()メソッドを呼び出します。
そして、 Add()メソッドの引数にリストの要素を指定します。
foreach (var item in myDict)
{
items.Add(item);
}
上記のforeachループは、ループしたDictionary(連想配列)の要素を用意したリストに格納します。
また、ここまでの処理で、Dictionaryの要素がKeyValuePairのリストに変換されます。
使用例
using System;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
Dictionary<string, int> numbers = new Dictionary<string, int>()
{
{ "one", 1 },
{ "two", 2 },
{ "three", 3 },
{ "four", 4 },
{ "five", 5 },
};
List<KeyValuePair<string, int>> items = new List<KeyValuePair<string, int>>();
foreach (var item in numbers)
{
items.Add(item);
}
Console.WriteLine(String.Join(",", items)); //[one, 1],[two, 2],[three, 3],[four, 4],[five, 5]
}
}
まとめ
Dictionary(連想配列)の要素をKeyValuePairのリストに変換する方法は、次の3つです。
- List<T>()を使う方法
List<KeyValuePair<TKey, TValue>> items = new List<KeyValuePair<TKey, TValue>>(myDict);
- ToList()を使う方法
List<KeyValuePair<TKey, TValue>> items = myDict.ToList();
- foreachループを使う方法
List<KeyValuePair<TKey, TValue>> items = new List<KeyValuePair<TKey, TValue>>();
foreach (var item in myDict) { items.Add(item); }
コメント