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

System.Linqを使ってDictionary(連想配列)の要素をKeyValuePairのリストに変換するには、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]
}
}
コメント