どうも、ちょげ(@chogetarou)です。
Dictionary(辞書)で指定した条件を満たす要素を検索する方法を紹介します。
方法

Dictionary(辞書)で指定した条件を満たす要素を検索する方法は、2つあります。
FirstOrDefault()
1つは、FirstOrDefault()を使う方法です。
まず、System.Linqを導入します。
using System.Linq;
次に、Dictionary(辞書)からFirstOrDefault()を呼び出します。
FirstOrDefault()の引数に、条件式を返すラムダ式を指定します。
条件式では、Dictionaryのキーを引数のKeyプロパティ、値を引数のValueプロパティで表現します。
//item.Keyでキー、item.Valueで値を取得
var result = dict.FirstOrDefault(item => 条件式);
上記のFirstOrDefault()は、条件式でTrueを返した要素を取得します。
使用例
using System;
using System.Linq;
using System.Collections.Generic;
public class Sample
{
public static void Main()
{
Dictionary<string, int> numbers = new Dictionary<string, int>()
{
{ "one", 1 },
{ "two", 2 },
{ "three", 3 },
{ "four", 4 },
{ "five", 5 },
};
var result = numbers.FirstOrDefault(item => item.Value % 2 == 0);
Console.WriteLine(result);
}
}
出力:
[two, 2]
Where()
もう1つは、Where()を使う方法です。
まず、System.Linqを導入します。
using System.Linq;
次に、Dictionary(辞書)からWhere()を呼び出します。
Where()の引数に、要素の条件式を返すラムダ式を指定します。
要素の条件式では、キーを引数のKeyプロパティ、値を引数のValueプロパティで表現します。
//item.Keyでキー、item.Valueで値を取得
var result = dict.Where(item => 条件式);
上記のSelect()は、Where()のラムダ式でTrueを返した全ての要素を取得します。
使用例
using System;
using System.Linq;
using System.Collections.Generic;
public class Sample
{
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(item => item.Value % 2 == 0)
.ToDictionary(item => item.Key, item => item.Value);
foreach(var item in result){
Console.WriteLine(item);
}
}
}
出力:
[two, 2]
[four, 4]
まとめ
Dictionary(辞書)で条件を満たす要素を検索する方法は、次の2つです。
- FirstOrDefault()を使う方法
var result = dict.FirstOrDefault(item => 条件式);
- Where()を使う方法
var result = dict.Where(item => 条件式);
コメント