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

Dictionary(連想配列)のValue(値)をリスト(List)に変換する方法は、3つあります。
Values + List<T>()
1つ目は、ValuesとList<T>を使う方法です。
まず、「new List<T>()」を記述します。
そして、List<T>()の引数で、DictionaryのValuesプロパティにアクセスします。
List<T> keys = new List<T>(myDict.Values);
上記のList<T>()は、ValuesプロパティにアクセスしたDictionary(連想配列)の値をリストに変換します。
使用例
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<int> values = new List<int>(numbers.Values);
Console.WriteLine(String.Join(",", values));//1,2,3,4,5
}
}
Values + ToList()
2つ目は、ValuesとToList()を使う方法です。
まず、System.Linqを導入します。
using System.Linq;
Dictionary()のValuesプロパティにアクセスします。
そして、DictionaryのValuesプロパティからToList()を呼び出します。
List<T> values = dict.Values.ToList();
上記のToList()は、Dictionary(連想配列)の値をリストに変換します。
使用例
using System;
using System.Linq;
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<int> values = numbers.Values.ToList();
foreach (var value in values)
{
Console.WriteLine(value);
}
}
}

Select() + ToList()
3つ目は、Select()とToList()を使う方法です。
まず、System.Linqを導入します。
using System.Linq;
次に、DictionaryからSelect()を呼び出します。
Select()の引数に、引数のValueプロパティを返すラムダ式を指定します。
そして、Select()からToList()を呼び出します。
List<T> values = dict.Select(item => item.Value).ToList();
上記のdict.Select.ToList()は、Select()を呼び出したDictionary(連想配列)の値をリストに変換します。
使用例
using System;
using System.Linq;
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<int> values = numbers.Select(item => item.Value).ToList();
Console.WriteLine(String.Join(",", values));//1,2,3,4,5
}
}
まとめ
Dictionary(連想配列)の値(value)をリスト(List)に変換する方法は、次の3つです。
- ValuesとList<T>()を使う方法
List<T> values = new List<T>(myDict.Values);
- ValuesとToList()を使う方法
List<T> values = dict.Values.ToList();
- Select()とToList()を使う方法
List<T> values = dict.Select(item => item.Value).ToList();
コメント