[C#]Dictionary(連想配列)のキーをリストに変換するには?

どうも、ちょげ(@chogetarou)です。

Dictionary(連想配列)のキーをリストに変換する方法を紹介します。

スポンサーリンク

方法

インターフェース, インターネット, プログラム, ブラウザ, Www

Dictionary(連想配列)のキーをリストに変換する方法は、3つあります。

Keys + List<T>()

1つ目は、KeysとList<T>を使う方法です。

まず、「new List<T>()」を記述します。

そして、List<T>()の引数で、DictionaryのKeysプロパティにアクセスします。

List<T> keys = new List<T>(myDict.Keys);

上記のList<T>()は、Keysプロパティにアクセスした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<string> keys = new List<string>(numbers.Keys);
	    
	    Console.WriteLine(String.Join(",", keys));//one,two,three,four,five
	}
}

Keys + ToList()

2つ目は、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
	}
}

Select() + ToList()

3つ目は、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
	}
}

まとめ

Dictionary(連想配列)のキーをリストに変換する方法は、次の3つです。

  • KeysとList<T>()を使う方法
    List<T> keys = new List<T>(myDict.Keys);
  • KeysとToList()を使う方法
    List<T> keys = dict.Keys.ToList();
  • Select()とToList()を使う方法
    List<T> keys = dict.Select(item => item.Key).ToList();

コメント

タイトルとURLをコピーしました