どうも、ちょげ(@chogetarou)です。
Dictionary(連想配列)の条件に合致する要素を全て削除する方法を紹介します。
方法

Dictionary(連想配列)の条件に合致する要素を全て削除する方法は、2つあります。
foreach
1つは、foreachを使う方法です。
まず、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(連想配列)から削除します。
使用例
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);
}
}
}
Where() + ToDictionary()
もう1つは、Where()と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となる要素を削除した辞書を返します。
使用例
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);
}
}
}
まとめ
Dictionary(連想配列)の条件に合致する要素を全て削除する方法は、次の2つです。
- foreachを使う方法
- Where()とToDictionary()を使う方法
コメント