どうも、ちょげ(@chogetarou)です。
Dictionary(辞書)で条件を満たす値(value)からキー(key)を取得する方法を紹介します。
方法

Dictionary(辞書)で条件を満たす値(value)からキー(key)を取得する方法は、2つあります。
FirstOrDefault()
1つは、FirstOrDefault()を使う方法です。
まず、System.Linqを導入します。
using System.Linq;
次に、Dictionary(辞書)からFirstOrDefault()を呼び出します。
FirstOrDefault()の引数に、値(Value)の条件式を返すラムダ式を指定します。
値(value)の条件式では、Dictionaryの値を引数のValueプロパティで表現します。
そして、FirstOrDefault()のKeyプロパティにアクセスします。
//item.Valueで値を取得
var result = dict.FirstOrDefault(item => 値の条件式).Key;
上記のKeyプロパティは、条件式で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 % 3 == 0).Key;
Console.WriteLine(result);
}
}
出力:
three
Where()
もう1つは、Where()を使う方法です。
まず、System.Linqを導入します。
using System.Linq;
次に、Dictionary(辞書)からWhere()を呼び出します。
Where()の引数に、値(Value)の条件式を返すラムダ式を指定します。
値(value)の条件式では、Dictionaryの値を引数のValueプロパティで表現します。
そして、Where()からSelect()を呼び出します。
Select()の引数に、引数のKeyプロパティを返すラムダ式を指定します。
//item.Valueで値を取得
var result = dict.Where(item => 値の条件式)
.Select(item => item.Key);
上記の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 },
};
//奇数の値からキーを取得
var result = numbers.Where(item => item.Value % 2 == 1)
.Select(item => item.Key);
foreach(var item in result)
{
Console.WriteLine(item);
}
}
}
出力:
one
three
five
まとめ
Dictionary(辞書)で条件を満たす値(value)からキー(Key)を取得する方法は、次の2つです。
- FirstOrDefault()を使う方法
var result = dict.FirstOrDefault(item => 値の条件式).Key;
- Where()を使う方法
var result = dict.Where(item => 値の条件式).Select(item => item.Key);
コメント