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

System.Linqを使ってDictionary(連想配列)のキーをリストに変換する方法は、2つあります。
Select() + ToList()
1つは、Select()とToList()を使う方法です。
まず、System.Linqを導入します。
using System.Linq;
次に、DictionaryからSelect()を呼び出します。
Select()の引数に、引数のkeyプロパティを返すラムダ式を指定します。
そして、Select()からToList()を呼び出します。
List<T> keys = dict.Select(item => item.Key).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<string> keys = numbers.Select(item => item.Key).ToList();
Console.WriteLine(String.Join(",", keys));//one,two,three,four,five
}
}
Keys + ToList()
もう1つは、KeysプロパティとToList()を使う方法です。
まず、System.Linqを導入します。
using System.Linq;
Dictionary()のKeysプロパティにアクセスします。
そして、DictionaryのKeysプロパティからToList()を呼び出します。
List<T> keys = dict.Keys.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<string> keys = numbers.Keys.ToList();
Console.WriteLine(String.Join(",", keys));//one,two,three,four,five
}
}
まとめ
Dictionary(連想配列)のキーをリストに変換する方法は、次の2つです。
- Select()とToList()を使う方法
List<T> keys = dict.Select(item => item.Key).ToList();
- KeysとToList()を使う方法
List<T> keys = dict.Keys.ToList();
コメント