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

Select()を使ってDictionary(連想配列)のキーをリストに変換するには、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
}
}
コメント