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

C#

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

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

スポンサーリンク

方法

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

foreachを使ってDictionary(連想配列)の条件を満たす要素を全て削除するには、Where()メソッドとRemove()メソッドを使います。

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

using System.Linq;

次に、foreachのループを記述します。

ループ対象でDictionaryからWhere()メソッドを呼び出し、Where()メソッドからToList()を呼び出します。

Whereメソッドの引数にラムダ式を指定し、ラムダ式で削除する条件を指定します。

あとは、foreachのループ処理で、DictionaryからRemove()メソッドを呼び出します。

Remove()メソッドの引数に、foreachの変数のKeyプロパティを指定します。

foreach (var item in dict.Where(x => 条件式).ToList())
{
    dict.Remove(item.Key);
}

上記のforeachループは、Where()のラムダ式で返す条件式を満たす要素をDictionary(連想配列)から削除します。

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 },
	    };
	    
	    foreach (var item in numbers.Where(x => x.Value % 2 == 0).ToList())
	    {
	        numbers.Remove(item.Key);
	    }
	    
	    foreach (var i in numbers)
	    {
	        Console.WriteLine("{0} : {1}", i.Key, i.Value);
	    }
	}
}

コメント

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