[C#]Where()でDictionary(連想配列)の条件を満たす要素を全削除するには?

C#

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

Where()を使ってDictionary(連想配列)の条件を満たす要素を全て削除する方法を紹介します。

スポンサーリンク

方法

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

Where()を使ってDictionary(連想配列)の条件を満たす要素を全て削除するには、ToDictionary()を使います。

まず、System.Linqを導入します。

using System.Linq;

次に、DictionaryからWhere()メソッドを呼び出し、Where()メソッドの引数にラムダ式を指定します。

ラムダ式で削除する要素でFalseとなる条件式を指定します。

あとは、Where()メソッドからToDictionary()を呼び出します。

ToDictionary()の第1引数に引数のKeyプロパティを返すラムダ式、第2引数に引数のValueプロパティを返すラムダ式を指定します。

Dictionary<string, int> result = dict
   .Where(x => 削除する要素でFalseとなる条件式)
   .ToDictionary(x => x.Key, y => y.Value);

上記のWhere().ToDictionary()は、Where()のラムダ式で返す条件式でFalseとなる要素を削除した辞書を返します。

Where()のラムダ式は、引数でDictionaryの要素を取得できます。

また、Dictionaryの要素のキーはKeyプロパティ、要素の値はValueプロパティで取得します。

使用例

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 },
	    };
	    
	    Dictionary<string, int> result = numbers
	       .Where(x => x.Value <= 3)
	       .ToDictionary(x => x.Key, y => y.Value);
	    
	    foreach (var i in result)
	    {
	        Console.WriteLine("{0} : {1}", i.Key, i.Value);
	    }
	}
}

コメント

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